0

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

Come here! where?             not here!

而是得到

Come here!                     where? not here!

当我使用代码时

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

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

4

3 回答 3

3

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

cout << left << setw(30) << (string("Come here!") + " where? ") << setw(20) << "not here!" << endl;
于 2010-03-12T22:28:10.460 回答
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;
}
于 2010-03-12T22:34:58.833 回答
1

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

cout << left << setw(30) << (string("Come here!") + string(" where? ")) << setw(20) << "not here!" << endl;
于 2010-03-12T22:29:21.600 回答