C++ 在正确的列中显示文本

C++ 在正确的列中显示文本,c++,cout,setw,C++,Cout,Setw,在得到一个有用的答案后,我遇到了另一个问题:在我希望显示的列中显示两个或多个字符串。作为我遇到的问题的一个例子,我想要以下输出: Come here! where? not here! 但相反,你会得到 Come here! where? not here! 当我使用代码时 cout << left << setw(30) << "Come here!" << " where? "

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

Come here! where?             not here!
但相反,你会得到

Come here!                     where? not here!
当我使用代码时

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

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

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

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

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

cout
setw
只包含下一个字符串,因此需要将它们串联起来

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

cout
setw
只包含下一个字符串,因此需要将它们串联起来

cout << left << setw(30) << (string("Come here!") + string(" where? ")) << setw(20) << "not here!" << endl;
cout如上所述,
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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
细流ss;
ss如前所述,
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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
细流ss;

ss-Um,
(string(“过来!”)+“where?”)
就足够了,它可以保护一个
std::string
ctor。(这并不重要,我们什么时候可以写
“过来!哪里?”
,但是,嘿,我学究……)是的,它节省了输入,但在我看来,它打破了对称性,降低了可读性。这并不是说它节省了输入,它节省了对一个ctor的一次调用,因此,run-time.Um,
(string(“过来!”)+“where?”)
就足够了,并且可以保护一个
std::string
ctor。(这并不重要,我们什么时候可以写
“过来!哪里?”
,但是,嘿,我很学究……)是的,它可以节省键入时间,但在我看来,它打破了对称性,降低了可读性。这并不是说它可以节省键入时间,它可以节省对ctor的一次调用,因此是运行时。