题意如下:
输入若干行代码,要求各列单词的左边界对齐且尽量靠左。单词之间至少要空一格。每个单词不超过80个字符,每行不超过180个字符,一共最多1000行。
代码展示:
#include <iostream>
#include <vector>
#include <string.h>
#include <sstream>
using namespace std;
const int maxLine = 1005; //最大行
vector<string> code[maxLine];
int col_max_len[185]; //每一列单词的字母最大数
int main(){
int row = 0,col = 0;
string line,temp;
memset(col_max_len, 0, sizeof(col_max_len));
while(getline(cin,line)){
if(line[0] == '#'){ //文本结束标志
break;
}
stringstream ss(line); //每一行以空格划分单词
while(ss>>temp){
col_max_len[col] = max(col_max_len[col],(int)temp.size()); //计算列单词字母最大值
code[row].push_back(temp);
col++;
}
row++; col = 0;
}
//格式输出
for(int i = 0; i < row;i++){
int j;
for(j = 0; j < code[i].size() - 1; j++){
for(int k = 0; k < code[i][j].size();k++)cout<<code[i][j][k]; //输出字符
for(int k = 0; k <= col_max_len[j] - code[i][j].size();k++)cout<<' '; //输出空格
}
cout<<code[i][j]<<endl; //每一行最后一个字母后换行
}
return 0;
}
测试结果: