在正确的列中显示文本
在此处得到有用的答案后,我遇到了另一个问题:在我希望显示的列中显示两个或多个字符串。对于我遇到的问题的一个示例,我想要这个输出:
Come here! where? not here!
但是
Come here! where? not here!
代码时
cout << left << setw(30) << "Come here!" << " where? " << setw(20) << "not here!" << endl;
当我使用我确信(我认为)的 得到两列的宽度都可以包含两个字符串,但无论我将列的宽度设置多大,错误仍然存在。
After getting a helpful answer here, I have run into yet another problem: displaying two or more strings in the column I want it to be displayed in. For an example of the problem I have, I want this output:
Come here! where? not here!
but instead get
Come here! where? not here!
when I use the code
cout << left << setw(30) << "Come here!" << " where? " << setw(20) << "not here!" << endl;
I made sure (I think) that the width of both columns could contain the two strings, but no matter how large I set the width of the columns to be, the error is still there.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该将每列的内容打印为单个字符串,而不是多个连续的字符串,因为
setw()
仅格式化下一个要打印的字符串。因此,您应该在打印之前连接字符串,例如使用string::append()
或+
:You should print the contents of each column as a single string, instead of multiple consecutive strings, because
setw()
only formats the next string to be printed. So you should concatenate the strings before printing, using e.g.string::append()
or+
:如前所述,
setw()
仅适用于下一个输入,而您正尝试将其应用于两个输入。其他建议的替代方案使您有机会使用变量代替文字常量:
As stated,
setw()
only applies to the next input, and you are trying to apply it to two inputs.An alternative to the other suggestions which gives you a chance to use variables in place of literal constants:
setw
仅覆盖下一个字符串,因此您需要连接它们。setw
only covers the next string, so you'll need to concatenate them.