奇怪的cout行为

发布于 2024-11-28 17:17:17 字数 332 浏览 0 评论 0原文

我在 Ubuntu 上编译了一个为 Windows 开发(并在 Windows 上运行)的程序。在 Ubuntu 上,我看到这段代码:

string s = values_[9];
cout << s << endl;
cout << s << "x\n";

产生此输出:

high
xigh

第二行的预期输出是“highx”。我知道values_[9]的值最初是从文件中读取的(在Windows上写入)。打印其他字符串似乎工作正常。

这是怎么回事?

I compiled on Ubuntu a program that was developed for (and works on) Windows. On Ubuntu, I see this code:

string s = values_[9];
cout << s << endl;
cout << s << "x\n";

producing this output:

high
xigh

The expected output for the second line is "highx". I know that the value of values_[9] is originally read from a file (written on Windows). Printing other strings seems to work normally.

What's going on here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

缺⑴份安定 2024-12-05 17:17:17

运行该命令,其输出通过 cat -A 传送。可能是 s 的值或 endl 生成的输出为您提供了一个 '\r' 字符,该字符通常会将光标发回到该行的开头。

编辑:进一步思考,杂散的 '\r' 几乎肯定在 s 中,而不是在 endl 生成的输出中。我原以为可能会发生一些有趣的语言环境问题,但是 s 等于 "high\r" 可以解释这些症状。

EDIT2:如果您的系统没有 cat -A (它是 GNU 扩展),请尝试 cat -v 或者,如果您绝望,od - c.

Run the command with its output piped through cat -A. Probably either the value of s, or the output produced by endl is giving you a '\r' character, which typically sends the cursor back to the beginning of the line.

EDIT: On further thought, the stray '\r' is almost certainly in s, not in the output produced by endl. I had thought there might be some funny locale stuff going on, but having s equal to "high\r" explains the symptoms.

EDIT2: If your system doesn't have cat -A (it's a GNU extension), try cat -v or, if you're desperate, od -c.

可是我不能没有你 2024-12-05 17:17:17

您要打印的字符串中有一个回车符'\r'。发生的情况是,您先打印 high,然后打印回车符,这会将光标放回行首。然后,当您打印 x 时,它会覆盖该行的第一个字母。

您应该从源文件中删除回车符(例如使用 dos2unix(1)或许多其他选项),或者更改代码以在读入文件后去除回车符。

The string you're printing has a carriage return '\r' in it. What's happening is that you're printing high, then the carriage return, which puts the cursor back on the start of the line. Then, when you print the x, it overwrites the first letter on the line.

You should either remove the carriage return from the source file (e.g. with dos2unix(1) or many other options), or change your code to strip the carriage return after reading the file in.

许仙没带伞 2024-12-05 17:17:17

可能发生的情况是 values_[9] 中有一个 \r

What is probably happening, is that there is a \r in values_[9].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文