Programming Challenges 习题 3.8.8

PC/UVa:110308/848

Fmt

根据题目意思模拟就好了,但是题目中的规则有些不容易理解,这里总结一下:

  • 每行最多72个字符。
  • 长度大于72的单词单独占一行
  • 空行还是空行,也要去掉行尾空格
  • 当一行的开头有空格的时候,当作新的一段处理

根据上面描述的方式,应该是依次读取每一段,也就是程序里的strPara,然后针对这一段中的每个单词strWord和前导空格strSpace,判断是否可以在该行进行输出。

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

#define MAX_LEN 72

using namespace std;

int main()
{
	string strLine;
	vector<string> vecstrText;
	while (getline(cin, strLine)){
		while (!strLine.empty() && strLine.back() == ' ') strLine.pop_back();
		vecstrText.push_back(strLine);
	}
	size_t idx = 0;
	while (idx < vecstrText.size()){
		if (vecstrText[idx].empty()){
			cout << endl;
			idx++;
		}
		else{
			string strPara(vecstrText[idx++]);
			while (idx < vecstrText.size()){
				if (!vecstrText[idx].empty() && vecstrText[idx][0] != ' '){
					strPara.push_back(' ');
					strPara += vecstrText[idx++];
				}
				else break;
			}
			//cout << strPara << endl;
			size_t len = 0, i = 0, j = 0;
			while (i < strPara.size()){
				string strWord, strSpace;
				//跳过前导空格,因为已经去除了行尾空格,所以不会超出范围
				while (strPara[j] == ' ') strSpace.push_back(strPara[j++]);
				//读取当前单词至下一个空格
				while (j < strPara.size() && strPara[j] != ' ') strWord.push_back(strPara[j++]);
				if (len + strSpace.size() + strWord.size() <= MAX_LEN){
					cout << strSpace << strWord;
					len += strSpace.size() + strWord.size();
					i = j;
				}
				else{
					cout << endl;
					cout << strWord;
					len = strWord.size();
					i = j;
				}
			}
			cout << endl;
		}
	}
	return 0;
}
/*
   Unix fmt

The unix fmt program reads lines of text, combining
and breaking lines so as to create an
output file with lines as close to without exceeding
72 characters long as possible.  The rules for combining and breaking
lines are as follows.

   1.  A new line may be started anywhere there is a space in the input.
If a new line is started, there will be no trailing blanks at the
end of the previous line or at the beginning of the new line.

   2.  A line break in the input may be eliminated in the output, provided
it is not followed by a space or another line break.  If a line
break is eliminated, it is replaced by a space.
*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值