在正确的列中显示文本

发布于 2024-08-24 22:41:39 字数 564 浏览 6 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

ゝ杯具 2024-08-31 22:41:39

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

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

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 +:

cout << left << setw(30) << (string("Come here!") + " where? ") << setw(20) << "not here!" << endl;
落墨 2024-08-31 22:41:39

如前所述,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;
}

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:

#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;
}
初熏 2024-08-31 22:41:39

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

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

setw only covers the next string, so you'll need to concatenate them.

cout << left << setw(30) << (string("Come here!") + string(" where? ")) << setw(20) << "not here!" << endl;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文