题
在得到有用的回答 在这里,, 我遇到的又一个问题:显示两个或多个字符串中列我想这是显示。对于该问题的示例,我有,我想这样输出:
Come here! where? not here!
但不是得到
Come here! where? not here!
当我使用的代码
cout << left << setw(30) << "Come here!" << " where? " << setw(20) << "not here!" << endl;
我确信(I think)的宽度均列可能包含两个串,但无论如何大我设置宽度的列,误差仍然存在。
解决方案
作为说明, setw()
仅适用于下一个输入,并且你正试图将其应用于两个投入。
一个替代的其他建议,这些建议给你一个机会,以使用的变量的地方的文字constants:
#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;
}
其他提示
你应该打印内容的每一列作为一个单一串,而不是多个连串的,因为 setw()
唯一的格式,下一串来进行打印。所以你应该串连串前印刷,例如使用 string::append()
或 +
:
cout << left << setw(30) << (string("Come here!") + " where? ") << setw(20) << "not here!" << endl;
setw
只涵盖的下一串,所以只需要连接。
cout << left << setw(30) << (string("Come here!") + string(" where? ")) << setw(20) << "not here!" << endl;
不隶属于 StackOverflow