【问题标题】:Displaying text in correct column在正确的列中显示文本
【发布时间】:2010-03-12 22:20:53
【问题描述】:

在得到有用的答案here 后,我遇到了另一个问题:在我希望显示的列中显示两个或多个字符串。对于我遇到的问题的示例,我想要这个输出:

Come here! where?             not here!

而是得到

Come here!                     where? not here!

当我使用代码时

cout << left << setw(30) << "Come here!" << " where? " << setw(20) << "not here!" << endl;

我确定(我认为)两列的宽度都可以包含两个字符串,但是无论我将列的宽度设置多大,错误仍然存​​在。

【问题讨论】:

    标签: c++ cout setw


    【解决方案1】:

    您应该将每一列的内容打印为单个字符串,而不是多个连续的字符串,因为setw() 仅格式化要打印的下一个字符串。因此,您应该在打印之前连接字符串,例如使用string::append()+

    cout << left << setw(30) << (string("Come here!") + " where? ") << setw(20) << "not here!" << endl;
    

    【讨论】:

      【解决方案2】:

      如上所述,setw() 仅适用于下一个输入,而您正尝试将其应用到两个输入。

      其他建议的替代方案,让您有机会使用变量代替文字常量:

      #include <iostream>
      #include <sstream>
      #include <iomanip>
      using namespace std;
      
      int main()
      {
          stringstream ss;
          ss << "Come here!" << " where?";
          cout << left << setw(30) << ss.str() << setw(20) << "not here!" << endl;
          return 0;
      }
      

      【讨论】:

        【解决方案3】:

        setw 仅涵盖下一个字符串,因此您需要将它们连接起来。

        cout << left << setw(30) << (string("Come here!") + string(" where? ")) << setw(20) << "not here!" << endl;
        

        【讨论】:

        • 嗯,(string("Come here!") + " where? ") 就足够了,可以保护一个std::string ctor。 (没关系,我们什么时候可以写"Come here! where? ",但是,嘿,我很迂腐......)
        • 是的,它可以节省打字时间,但 IMO 会破坏对称性并使其可读性降低。
        • 它不是节省打字,而是节省了对 ctor 的一次 调用,因此节省了运行时间。
        猜你喜欢
        • 2013-09-12
        • 1970-01-01
        • 2012-08-09
        • 2014-02-11
        • 1970-01-01
        • 2014-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多