Есть довольно много способов сделать это, но вот один довольно простой и легкий.
#include <sstream>
#include <string>
#include <iostream>
void wrap(std::string const &input, size_t width, std::ostream &os, size_t indent = 0) {
std::istringstream in(input);
os << std::string(indent, ' ');
size_t current = indent;
std::string word;
while (in >> word) {
if (current + word.size() > width) {
os << "\n" << std::string(indent, ' ');
current = indent;
}
os << word << ' ';
current += word.size() + 1;
}
}
int main() {
char *in = "There was a time when he would have embraced the change that was coming. In his youth he"
" sought adventure and the unknown, but that had been years ago. He wished he could go back and learn"
" to find the excitement that came with change but it was useless. That curiousity had long ago left"
" him to where he had come to loathe anything that put him out of his comfort zone.";
wrap(in, 72, std::cout, 0);
return 0;
}
Это подразумевает, что вы хотите удалить дополнительный пробел, который может присутствовать во входной строке, поэтому, если (например) вы начали с текста, отформатированного для 60 столбцов с 5-символьным символом отступ:
There was a time when he would have embraced the change
that was coming. In his youth he sought adventure and
the unknown, but that had been years ago. He wished he
could go back and learn to find the excitement that
came with change but it was useless. That curiousity
had long ago left him to where he had come to loathe
anything that put him out of his comfort zone.
... но вы просили, чтобы он был заключен в 72 столбца без отступа, он избавился бы от пробела, использовавшегося для предыдущего отступа, поэтому вот так:
There was a time when he would have embraced the change that was coming.
In his youth he sought adventure and the unknown, but that had been
years ago. He wished he could go back and learn to find the excitement
that came with change but it was useless. That curiousity had long ago
left him to where he had come to loathe anything that put him out of his
comfort zone.
Другая возможность, особенно если вы хотите обернуть все выходные данные в конкретный поток, будет заключаться в использовании потокового переноса с переносом слов, который я разместил в другой ответ .