简体   繁体   English

奇怪的行为

[英]strange cout behaviour

I compiled on Ubuntu a program that was developed for (and works on) Windows.我在 Ubuntu 上编译了一个为 Windows 开发(并适用于)的程序。 On Ubuntu, I see this code:在 Ubuntu 上,我看到以下代码:

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

producing this output:生产这个 output:

high
xigh

The expected output for the second line is "highx".第二行的预期 output 是“highx”。 I know that the value of values_[9] is originally read from a file (written on Windows).我知道 values_[9] 的值最初是从文件中读取的(写在 Windows 上)。 Printing other strings seems to work normally.打印其他字符串似乎工作正常。

What's going on here?这里发生了什么?

Run the command with its output piped through cat -A .使用通过cat -A管道传输的 output 运行命令。 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.可能s的值或由endl生成的 output 为您提供了一个'\r'字符,这通常会将 cursor 发送回行首。

EDIT: On further thought, the stray '\r' is almost certainly in s , not in the output produced by endl .编辑:进一步考虑,流浪'\r'几乎肯定在s中,而不是在endl生产的 output 中。 I had thought there might be some funny locale stuff going on, but having s equal to "high\r" explains the symptoms.我原以为可能会发生一些有趣的语言环境,但是s等于"high\r"可以解释这些症状。

EDIT2: If your system doesn't have cat -A (it's a GNU extension), try cat -v or, if you're desperate, od -c . EDIT2:如果您的系统没有cat -A (它是 GNU 扩展),请尝试cat -v ,或者,如果您很绝望,请尝试od -c

The string you're printing has a carriage return '\r' in it.您正在打印的字符串中有一个回车符'\r' What's happening is that you're printing high , then the carriage return, which puts the cursor back on the start of the line.发生的事情是您打印high ,然后是回车,这使 cursor 回到行首。 Then, when you print the x , it overwrites the first letter on the line.然后,当您打印x时,它会覆盖该行的第一个字母。

You should either remove the carriage return from the source file (eg with dos2unix(1) or many other options), or change your code to strip the carriage return after reading the file in.您应该从源文件中删除回车符(例如使用dos2unix(1)或许多其他选项),或者在读入文件后更改代码以去除回车符。

What is probably happening, is that there is a \r in values_[9] .可能发生的事情是values_[9]中有一个\r

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM