Uva1593 - Alignment of Code

9 篇文章 0 订阅

一.题目

题目链接:Uva1593

二.思路

用2个向量,1个向量来保存每一行的单词,1个向量用来保存每一列中的最长单词的长度,最后在输出的时候进行处理。详细的请看代码注释。

三.源代码

#include<iostream>
#include<vector>
#include<string.h>
#include<sstream>
#include<iomanip>
using namespace std;
const int max_n=1000+5;
int main()
{
    string code;             //用来保存一行的字符
    int len=0,row=0,col=0,cout_width=0;
    vector<string> words[max_n];   //用来保存一行中的每个单词
    vector<int> max_len(180,0);    //保存每列中的最长单词的长度
    string word="";               //临时保存每个单词
    while(getline(cin,code))      //读取一行
    {
        istringstream is(code);   //将code作为一个字符串流
        while(is>>word)           //使得我们可以像cin一样输入字符串
        {
            words[row].push_back(word);    //将单词添加到当前行的容器内
            len=word.length();            //比较当前单词长度和之前同列最大长度单词哪个大
            if(len>max_len[col])
            max_len[col]=len;
            col++;                        //列数加1
        }
        col=0;           //重置列数
        row++;
    }
    for(int i=0;i<row;i++)
    {
        /*
        从第一行开始迭代输出,在每一行中用迭代器进行遍历
        注意每一行的最后一列是不需要输出空格的
        */
        for(vector<string>::const_iterator iter = words[i].cbegin();iter!=words[i].cend()-1;iter++)
        {
            cout_width=max_len[iter-words[i].cbegin()];  //宽度控制为当前列最大单词长度
            cout.width(cout_width);
            cout<<left<<(*iter);   //输出靠左
            cout<<" ";       //单词之间要有一个空格划分
        }
        cout<<left<<(*(words[i].cend()-1));  //最后一列特殊处理
        cout<<endl;
    }
    return 0;
}

四.备注

若有不足之处,欢迎指出与相互探讨。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值