用C ++格式化文本

时间:2015-02-16 04:41:40

标签: c++ text formatting

所以我正在尝试为我在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';            

3 个答案:

答案 0 :(得分:2)

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

#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

BTW,您的原始代码可以简化为......

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 ++认为语句未完成直到它到达分号,并且代码中彼此相邻的双引号字符串文字会自动连接,就像内部双引号和空格被删除一样。

答案 1 :(得分:1)

您可以制作一个简单的功能

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?

答案 2 :(得分:1)

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

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