2010-03-12 69 views
0

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

Come here! where?    not here! 

而是得到

Come here!      where? not here! 

当我使用的代码

cout << left << setw(30) << "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()仅格式化要打印的下一个字符串。所以你应该在打印之前连接字符串,使用例如string::append()+

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

setw只覆盖了下一个字符串,所以你需要将它们串联。

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

嗯,'(字符串(“你过来”)+“在哪里?”)'会够了,保险一个'std :: string' ctor。 (这不是问题,我们什么时候可以写''来这里,在哪里?'',但是,嘿,我很迂腐...) – sbi 2010-03-12 22:39:20

+0

是的,它节省了打字,但它破坏了对称性,并使它不易读。 – 2010-03-12 23:28:16

+0

这并不是说它可以节省打字的时间,它可以节省一个_call_到一个ctor,从而节省运行时间。 – sbi 2010-03-14 10:35:53