PC/UVa:110308/848
根据题目意思模拟就好了,但是题目中的规则有些不容易理解,这里总结一下:
- 每行最多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.
*/