題目地址:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4468
題意分析:
輸入一連串的文本,行中包含有空格。要求對每行輸入進行對齊。
解題思路:
因爲輸入可能包含空格,要完整讀取一行需要使用getline()
,並且配合字符串流stringstream
讀入字符串進行處理。使用vector<string> ve[]
容器保存每一行的單詞,其可以看做一個二維數組。使用ve[i][j]
就可以獲取相應的單詞。再用一個數組保存每一列中的最長單詞的長度。最後格式化輸出就可以了
代碼如下:
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <string.h>
#include <sstream>
#include <algorithm>
using namespace std;
vector<string> ve[1100]; //保存每一行
int max_len[250]; //保存每一列中的最大單詞長度
void print(string s,int len){
for(int i = 0;i < s.size();i++)
cout<<s[i];
for(int j = 0;j < len - s.size();j++)
cout<<' ';
cout<<' ';
}
int main(void){
//freopen("data.in","r",stdin);
//freopen("data.out","w",stdout);
string line,code;
memset(max_len,0,sizeof(max_len));
int row = 0,col = 0;
//讀入輸入
while(getline(cin,line)){ //完整讀取一行到字符串中,包括空白字符(空格)。
stringstream ss(line); //構建一個字符串流。
while(ss>>code){
max_len[col] = max(max_len[col],(int)code.size());
col++;
ve[row].push_back(code);
}
row++,col = 0;
}
//格式輸出
for(int i = 0;i < row;i++){
int j = 0;
for(;j < ve[i].size() - 1;j++){
print(ve[i][j],max_len[j]);
}
cout<<ve[i][j]<<endl;
}
return 0;
}
解題反思:
還是覺得自己C++基礎是真的很差,輸入格式上就卡了很久,重要的一個地方就是需要配合getline()以及stringstream做字符串的輸入操作,希望自己以後能夠記住這種寫法。