第6论坛的一个问题:编写一个程序,从键盘上以任意方便的方法输入一段文章(文章中每个单词不会超过20个字母),然后打印出来。打印时每行的宽度必须为20字符。如果一行的最后一个单词超过了本行20个字符的范围,则应把它移到下一行去。在每个单词之间增加一些空格,以便使每行的末尾准确地处于第20个字符处。
我写了个把一个字符串句子按要求的列分行的函数。
#pragma warning(disable: 4786)
#include <string>
#include <vector>
#include <iostream>
#include <sstream>

using namespace std;

const char *getSpace(unsigned int n)


{
static string buf;
if (n > buf.size())

{
buf.assign(n, ' ');
}
return buf.c_str() + buf.size() - n;
}

void build_line(const vector< vector< string >::iterator > words, int total_spaces, string &line)


{
int i = words.size() - 1;
for (vector< vector< string >::iterator >::const_iterator word = words.begin();
word != words.end(); ++word)

{
line += **word;
if (i > 0)

{
const int sc = (total_spaces + i - 1) / i;
total_spaces -= sc;
line += getSpace(sc);
i--;
}
}
}

void text_line_feed(const char *text, int line_limit, vector< string > &out)


{
string buf(text);
vector< string > strings;
for(const char *word = strtok(buf.begin(), " \t\n"); word; word = strtok(NULL, " \t\n"))
strings.push_back(word);

vector< vector< string >::iterator > temp;
int len = 0;
for (vector< string >::iterator s = strings.begin(); s != strings.end(); ++s)

{
const int slen = s->length();
if (len + slen >= line_limit)

{
string line;
const int space_count = line_limit - len + temp.size();
build_line(temp, space_count, line);
out.push_back(line);
temp.clear();
len = 0;
}

len += slen + 1; // with at least one space
temp.push_back(s);
}
string line;
build_line(temp, temp.size() - 1, line); // 最后一行,不用算总空格数
out.push_back(line);
}

int main()


{
vector< string > lines;
text_line_feed("A great discovery solves a great problem but there is a grain of discovery in the solution of any problem.",
50, lines);
for (vector< string >::iterator line = lines.begin(); line != lines.end(); ++line)
printf("%s\n", line->c_str());
return 0;
}
