Uva1593 Alignment of Code 【vector,stream应用】【习题5-1】

13 篇文章 0 订阅
12 篇文章 0 订阅

题目:Alignment of Code

题意:按样例输出格式,各列左边界对齐且尽量靠左,单词之间至少要空一格。

思路:记录每个列最长的单词作为格式,输出补空格即可

输入时处理需要用stream,自己写的处理居然超时了!!!

头文件:#include <sstream>

istringstream stream(处理的字符串str);

while(stream >> temp) 这个可将其单词分隔出!

参考:点击打开  ; 入门经典--习题5-1--P135

代码:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <string.h>
#include <sstream>
using namespace std;
#define maxn 1005
vector<string>words[maxn];
int len[200];
int main()
{
    string str,temp;
    int cot = 0;
    memset(len,0,sizeof(len));
    while(getline(cin,str))
    {

        temp = "";
        int colNum = 0;
        //这个居然超时。。。
        /*for(int i=0;str[i]!='\0';i++)
        {
            if(str[i] != ' ')
            {
                temp += str[i];
                if(str[i+1] == ' '){
                    words[cot].push_back(temp);
                    len[colNum] = max(len[colNum],(int)temp.length());
                    colNum++;
                    temp = "";
                }
                if(str[i+1] == '\0'){
                    words[cot++].push_back(temp);
                    len[colNum] = max(len[colNum],(int)temp.length());
                    colNum++;
                    temp = "";
                }
            }

        }*/
        istringstream stream(str);
        while(stream >> temp)
        {
            words[cot].push_back(temp);
            len[colNum] = max(len[colNum],(int)temp.length());
            colNum++;
        }
        cot++;
    }
    int j;
    for(int i=0;i<cot;i++)
    {
        for(j=0;j<words[i].size()-1;j++)
        {
            cout << words[i][j];
            for(int k=0;k<len[j]-words[i][j].length()+1;k++)
                cout << " ";
        }
        cout << words[i][j] << endl;
        words[i].clear();
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值