UVa 1593 (水题 STL) Alignment of Code

话说STL的I/O流用的还真不多,就着这道题熟练一下。

用了两个新函数:

cout << std::setw(width[j]);    这个是设置输出宽度的,但是默认是在右侧补充空格

所以就要用cout.setf(ios::left);来设置一下左对齐。

 1 #include <iostream>

 2 #include <cstdio>

 3 #include <sstream>

 4 #include <vector>

 5 #include <string>

 6 #include <cstring>

 7 #include <algorithm>

 8 #include <iomanip>

 9 using namespace std;

10 

11 const int maxn = 1000 + 10;

12 int width[maxn];

13 vector<string> a[maxn];

14 

15 int main()

16 {

17     //freopen("in.txt", "r", stdin);

18     //freopen("out.txt", "w", stdout);

19 

20     string line, s;

21     int cnt = 0;

22     while(getline(cin, line))

23     {

24         stringstream ss(line);

25         while(ss >> s) a[cnt].push_back(s);

26         cnt++;

27     }

28 

29     int col = 0;

30     for(int i = 0; i < cnt; i++) { int t = a[i].size(); col = max(col, t); }

31     for(int i = 0; i < col; i++)

32     {

33         for(int j = 0; j < cnt; j++) if(i < a[j].size())

34         {

35             int t = a[j][i].length() + 1;

36             width[i] = max(width[i], t);

37         }

38     }

39     width[col - 1]--;

40     cout.setf(ios::left);   //左对齐

41     for(int i = 0; i < cnt; i++)

42     {

43         for(int j = 0; j < col && j < a[i].size(); j++)

44         {

45             if(j == a[i].size() - 1) cout << std::setw(a[i][j].length());

46             else cout << std::setw(width[j]);

47             cout << a[i][j];

48         }

49         puts("");

50     }

51 

52     return 0;

53 }
代码君

 

你可能感兴趣的:(code)