【问题标题】:Format output in a table, C++在表格中格式化输出,C++
【发布时间】:2011-07-19 23:16:59
【问题描述】:

如何在 C++ 中的表中将数据输出到控制台?在 C# 中有一个问题,但我在 C++ 中需要它。

这个,除了在 C++ 中:How To: Best way to draw table in console app (C#)

【问题讨论】:

    标签: c++ console format tabular


    【解决方案1】:

    以下是 iomanip 的一个小示例:

    #include <iostream>
    #include <iomanip>
    
    int main(int argc, char** argv) {
        std::cout << std::setw(20) << std::right << "Hi there!" << std::endl;
        std::cout << std::setw(20) << std::right << "shorter" << std::endl;
        return 0;
    }
    

    您还可以执行其他操作,例如设置浮点数的精度、在使用 setw 时更改用作填充的字符、输出基数为 10 以外的数字等等。

    http://cplusplus.com/reference/iostream/manipulators/

    【讨论】:

      【解决方案2】:

      你不能做一些与 C# 示例非常相似的事情吗:

      String.Format("|{0,5}|{1,5}|{2,5}|{3,5}|", arg0, arg1, arg2, arg3);
      

      喜欢:

      printf("|%5s|%5s|%5s|%5s|", arg0, arg1, arg2, arg3);
      

      这是我用来做这个的参考:http://www.cplusplus.com/reference/clibrary/cstdio/printf/

      【讨论】:

      • 对于表格输出,C 的 printf 胜过 C++ 可怕的 I/O。
      • @Walter 这绝对是问题所在 - 您可以填充以修复下溢,但要处理溢出,您需要所有逻辑和策略来“明智地”包装。 (从溢出回溯到最近的定界符,回退到边缘情况的未定界包装,然后担心每行格式。)这本身是一个相对简单的问题,但可能更多如果你是在一个不相关的项目上进行美学修饰,那么工作比它值得。
      【解决方案3】:

      我找不到我喜欢的东西,所以我做了一个。在https://github.com/haarcuba/text-table找到它

      这是它的输出示例:

      +------+------+----+
      |      |Sex   | Age|
      +------+------+----+
      |Moses |male  |4556|
      +------+------+----+
      |Jesus |male  |2016|
      +------+------+----+
      |Debora|female|3001|
      +------+------+----+
      |Bob   |male  |  25|
      +------+------+----+
      

      【讨论】:

        【解决方案4】:

        检查列值长度并记住值的长度以进行格式化。

        printf(" %-4s| %-10s| %-5s|\n", "ID", "NAME", "AGE");
        

        看看 MySQL shell 接口是如何设计的,它会给你一个好主意。

        【讨论】:

          猜你喜欢
          • 2021-08-17
          • 1970-01-01
          • 2017-02-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多