在 C++ 中格式化文本

Formatting text in C++

所以我正在尝试为我的第一个真正的 C++ 项目制作一个基于文本的小游戏。当游戏需要一大块文本时,好几段,我很难让它看起来漂亮。我想要统一的线长,为此我只需要在适当的地方手动输入换行符。是否有为我执行此操作的命令?我见过 setw() 命令,但如果超过宽度,它不会使文本换行。有什么建议吗?如果有帮助,这就是我现在正在做的事情。

cout << "    This is essentially what I do with large blocks of" << '\n';
cout << "    descriptive text. It lets me see how long each of " << '\n';
cout << "    the lines will be, but it's really a hassle, see? " << '\n';            

你可以做一个非常简单的函数

void print(const std::string& brute, int sizeline)
{
     for(int i = 0; i < brute.length(); i += sizeline)
          std::cout << brute.substr(i, sizeline) << std::endl;
}

int main()
{
     std::string mytext = "This is essentially what I do with large blocks of"
                          "descriptive text. It lets me see how long each of "
                          "1the lines will be, but it's really a hassle, see?";

     print(mytext, 20);

     return 0;
}

但是字会被删

输出:

This is essentially 
what I do with large
 blocks ofdescriptiv
e text. It lets me s
ee how long each of 
1the lines will be, 
but it's really a ha
ssle, see?

获取或编写一个库函数来自动插入适合特定输出宽度的前导空格和换行符是个好主意。该网站认为库建议与主题无关,但我在下面包含了一些代码 - 不是特别有效但易于理解。基本逻辑应该是在字符串中向前跳到最大宽度,然后向后移动,直到找到准备换行的空格(或者可能是连字符)...然后打印前导空格和剩余的空格线的一部分。继续直到完成。

#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. For some alternatives, see 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++ 认为该语句在遇到分号之前未完成,并且代码中彼此相邻出现的双引号字符串文字会自动连接起来,就好像内部双引号和空格已被删除一样。

github 上有处理文本格式的漂亮库,名为 cppformat/cppformat

通过使用它,您可以轻松地处理文本格式。