这道题纯手写,主要强化了C++流的学习
对于每个单词的最大长度,一开始想构造一个二维数组来储存各个位置的单词长度再循环取最大值,后面又想到可以一边遍历一边取最大值。
对于输出,学习了格式化输出,左对齐最大长度。
- 向量数组的用法。每一个下标对应一个向量,所以应该对Lines[i]使用vector的操作
- getline(cin,string)
- istringstream 和 stringstream 的用法区别:
istringstream s(str) 创建一个在str中读取字符串的流。
stringstream s 是创建一个针对string的流,需要用s.str(str)来读取字符串。 - string和vector都有.size()的操作。
#include<bits/stdc++.h>
using namespace std;
#define maxn 1005
vector <string> lines[maxn];
vector <int> len_of_words[maxn];
int main()
{
string s;
int n=0,maxwords=0;
int max_of_len[180]={0};
while(getline(cin,s))
{
stringstream liu;
string words;
liu.str(s);
int j=0;
while(liu>>words)
{
lines[n].push_back(words);
if (max_of_len[j]<words.size())
max_of_len[j]=words.size();
j++;
}
n++;
}
for (int i=0;i<n;i++)
{
int j=0;
for (;j<lines[i].size()-1;j++)
{
cout<< left <<setw(max_of_len[j])<<lines[i][j]<<' ';
}
cout<<lines[i][j]<<'\n';
}
return 0;
}