5.5 - 1

题目:https://vjudge.net/problem/UVA-1593

思路:用vector的数组模拟string的二位数组存储单词,记录下没列单词的最大长度,然后用setw设置位宽,左对齐输出单词即可。

注:每行的最后一列直接输出,不能设置列宽,否则会输出多余的空格

getline 和 stringstream 是网上看题意的时候看到别人的代码 觉得很有道理 就抄了思路 这道题最大的困难就在于空格 但其实书上介绍了一种方法避免空格 就是用字符串流来做一个转换 具体我也不很明白 需要看一点C++了

#include
#include
#include
#include
#include
using namespace std;
vector  v[1005];
string s;

int main(){
    int d[200] = {0};
    int count = -1; 
    while(getline(cin,s)){
        count++;
        string a;
        stringstream ss(s);
        while(ss >> a) {
        v[count].push_back(a);
        }
    
    }
    for(int i = 0; i < count ; i++)
        for(int j = 0 ; j < v[i].size();j++)
            if(v[i][j].size() > d[j])    d[j] = v[i][j].size();

    for(int i = 0; i < count ; i++){
        for( int j = 0; j < v[i].size(); j++){
            if(j == v[i].size() - 1)  printf("%s", v[i][j].c_str());
            else        printf("%-*s", d[j] + 1, v[i][j].c_str());
        }
        printf("\n");
    }
    return 0;
}

你可能感兴趣的:(5.5 - 1)