奇怪的cout行为
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
运行该命令,其输出通过
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 ofs
, or the output produced byendl
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 ins
, not in the output produced byendl
. I had thought there might be some funny locale stuff going on, but havings
equal to"high\r"
explains the symptoms.EDIT2: If your system doesn't have
cat -A
(it's a GNU extension), trycat -v
or, if you're desperate,od -c
.您要打印的字符串中有一个回车符
'\r'
。发生的情况是,您先打印high
,然后打印回车符,这会将光标放回行首。然后,当您打印x
时,它会覆盖该行的第一个字母。您应该从源文件中删除回车符(例如使用
dos2unix(1)
或许多其他选项),或者更改代码以在读入文件后去除回车符。
The string you're printing has a carriage return
'\r'
in it. What's happening is that you're printinghigh
, then the carriage return, which puts the cursor back on the start of the line. Then, when you print thex
, 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.可能发生的情况是
values_[9]
中有一个\r
。What is probably happening, is that there is a
\r
invalues_[9]
.