【问题标题】:C++ display text left and right in same rowC++在同一行左右显示文本
【发布时间】:2019-06-23 19:54:15
【问题描述】:

我想在 C++ 中输出一个完整的格式化控制台行(80 个字符)。

应该是这样的:

Some things on the left side some other on the right side

数据包含两个迭代器函数,它们返回 std::string 和固定文本。像这样的:

std::cout << (*some_iterator)->getID() << " some text:" << LOTSOFSPACES << (*some_other_iterator)->getName() << " some more text.";

结果应始终为 80 个字符。

我尝试使用字符串流并计算我必须创建的空间来处理 std::setw 和 std::setfill、std::left 和 std::right。但没有什么真正有效,大多数想法只是完全破坏了输出。

有什么想法吗?不幸的是,我不允许使用外部库。

【问题讨论】:

    标签: c++ formatting cout


    【解决方案1】:

    如果你能确定这两个部分总是少于 40 个字符(或者它们可以以任何其他方式分成两列),你可以这样做:

    std::string firstPart = (*some_iterator)->getID() + " some text:";
    std::string secondPart = (*some_other_iterator)->getName() + " some more text.";
    std::cout << std::setw(40) << std::left <<  firstPart 
              << std::setw(40) << std::right << secondPart;
    

    See it online

    更通用的解决方案是简单地计算字符串之间的间距并手动插入。这不需要具有已知长度的列:

    std::string firstPart = (*some_iterator)->getID() + " some text:";
    std::string secondPart = (*some_other_iterator)->getName() + " some more text.";
    std::size_t spacingSize = 80 - firstPart.length() - secondPart.length();
        //Add some code to check if spacingSize is not negative!
    std::cout << firstPart << std::string(spacingSize, ' ') << secondPart;
    

    See it online

    【讨论】:

    • 它不起作用,因为我使用的字符串不是恒定的。它们由一个迭代器和一个常量部分组成。我认为由于这个事实,它计算出错误的长度。输出出现乱码。
    • 迭代器没有任何区别。只要getID()getName() 返回有效的std::string(字符总和为&lt; 80),你应该是好的。我编辑了代码以使其更适合您的示例。
    • 好的。我的错。一个迭代器返回 int 而不是 std::string。我只是使用了错误的成员函数,因为它们的名称相似。
    【解决方案2】:

    您可以尝试将光标设置在该位置。 首先你必须添加库:

    #include <windows.h>
    

    现在你可以使用函数了:

    COORD c;
    c.X = x_coordinate;
    c.Y = y_coordinate;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
    

    【讨论】:

      猜你喜欢
      • 2013-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多