获取或编写一个库函数来自动插入适合特定输出宽度的前导空格和换行符将是一个好主意。这个网站认为图书馆推荐是题外话,但我在下面包含了一些代码 - 不是特别有效但易于理解。基本逻辑应该是在字符串中向前跳转到最大宽度,然后向后移动,直到找到准备换行的空格(或者可能是连字符)......然后打印前导空格和剩余的线的一部分。继续直到完成。
#include <iostream>
std::string fmt(size_t margin, size_t width, std::string text)
{
std::string result;
while (!text.empty()) // while more text to move into result
{
result += std::string(margin, ' '); // add margin for this line
if (width >= text.size()) // rest of text can fit... nice and easy
return (result += text) += '\n';
size_t n = width - 1; // start by assuming we can fit n characters
while (n > width / 2 && isalnum(text[n]) && isalnum(text[n - 1]))
--n; // between characters; reduce n until word breaks or 1/2 width left
// move n characters from text to result...
(result += text.substr(0, n)) += '\n';
text.erase(0, n);
}
return result;
}
int main()
{
std::cout << fmt(5, 70,
"This is essentially what I do with large blocks of "
"descriptive text. It lets me see how long each of "
"the lines will be, but it's really a hassle, see?");
}
这还没有经过彻底的测试,但似乎有效。看到它运行here。对于一些替代方案,请参阅this SO question。
顺便说一句,您的原始代码可以简化为...
cout << " This is essentially what I do with large blocks of\n"
" descriptive text. It lets me see how long each of\n"
" the lines will be, but it's really a hassle, see?\n";
...因为 C++ 认为该语句未完成,直到它碰到分号,并且在代码中彼此相邻出现的双引号字符串文字会自动连接,就好像内部双引号和空格已被删除一样。