UVALive4983 UVa1593 POJ3959 Alignment of Code【字符串流+输入输出】

Regionals 2010 >> Europe - Northeastern


问题链接UVALive4983 UVa1593 POJ3959 Alignment of Code

问题描述参见上文。

问题分析

  输入有若干行,每行有若干单词,让各行的单词对齐。这应该是一个单词矩阵。

  输出时,需要构造好这个矩阵,可以用向量数组来存储这个矩阵。同时,需要分别对各个列的单词计算其最长的长度。有了这两点,输出就不是问题了。

程序说明

数组maxlen[]用于存储各个列的单词的最长长度,maxlen[i]=k表示第i列单词的最长为k。

向量数组words[]用于存储各个行的单词,words[i]中存储第i行的各个单词。

C++的输出格式控制需要用到库iomanip。

参考链接:(略)



AC的C++语言程序:

/* UVALive4983 UVa1593 POJ3959 Alignment of Code */

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <cstring>
#include <iomanip>

using namespace std;

const int N = 180;
const int N2 = 1000;

int maxlen[N+1];
vector<string> words[N2];

int main()
{
    string s, t;

    memset(maxlen, 0, sizeof(maxlen));

    int lencount = 0;
    while(getline(cin, s)) {
        stringstream ss(s);

        int i = 0;
        while(ss >> t) {
            maxlen[i] = max((int)t.length(), maxlen[i]);
            words[lencount].push_back(t);
            i++;
        }
        lencount++;
    }

    cout << setiosflags(ios::left);
    for(int i=0; i<lencount; i++) {
        int j;
        for(j=0; j<(int)words[i].size()-1; j++)
            cout << setw(maxlen[j] + 1) << words[i][j];
        cout << words[i][j] << endl;
    }

    return 0;
}



原文地址:https://www.cnblogs.com/tigerisland/p/7563774.html