UVa 1593

题意

代码格式对齐

思路

用string流输入, 用stringstream切割并将每一小段字符串存到不定长数组vector < string > 中, 每次更新每行最多单词量和每列的最大列宽

记录

1.size_t

size_t 大概是容器size() 的返回值数据类型

size_t 类型表示任何对象所能达到的最大长度。它是无符号整数
关于size_t占用的空间百度百科的描述是:经测试发现,在32位系统中size_t是4字节的,而在64位系统中,size_t是8字节的,这样利用该类型可以增强程序的可移植性。

2.getline读取整行文本
string line;
getline(cin,line);

getline()的原型是istream& getline ( istream &is , string &str , char delim );
其中 istream &is 表示一个输入流,譬如cin;
string&str表示把从输入流读入的字符串存放在这个字符串中(可以自己随便命名,str什么的都可以);
char delim表示遇到这个字符停止读入,在不设置的情况下系统默认该字符为’ ’,也就是回车换行符(遇到回车停止读入)

3.setw( int n ) 设置输出对象宽度

默认右对齐输出, 但是可使用setiosflags(ios::left)设置为左对齐输出
使用setfill(‘char x’)使用x来填充空下的空格

#include <iostream>
#include <iomanip>    //setw( int n ) 函数所在头文件
#include <string>
using namespace std;

int main()
{
    string str;
    while( getline(cin,line) ){
            cout<<setw(10)<<setiosflags(ios::left)<<setfill('~')<<str<<endl;
            cout<<setw(10)<<setiosflags(ios::right)<<setfill('~')<<str<<endl;
            cout<<setw(10)<<setfill('~')<<str<<endl;
    }
    return 0;
}

样例输入输出
UVa 1593

AC代码

#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstdio>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

vector<string> Linewords[2000];  //有点形似二维数组
size_t len[200];

int main()
{
    string line, word;
    int m = 0, l = 0;  //记录单行中最多出现单词数量; 记录总共输入的行数
    while( getline(cin,line) )  //getline第三个参数默认是'
'换行符 结束读入
    {
        stringstream ss(line);
        int n = 0;
        while( ss >> word ){
            len[n] = max(len[n], word.size());
            n++;
            Linewords[l].push_back(word);
        }
        m = max(m,n);
        l++;
    }

    for( int i = 0; i < l; i++ )
    {
        int n = 0;
        size_t nmax = Linewords[i].size();
        //cout << nmax << endl;
        for( n = 0; n < nmax; n++ ){
            if( n != 0 )    cout << ' ';
            if( n != nmax-1 ) cout << setw(len[n]) << setiosflags(ios::left) << setfill(' ')<< Linewords[i][n];
            else  cout << Linewords[i][n];
        }
        cout << endl;
    }
    return 0;
}