Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange cout behaviour

Tags:

c++

cout

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?

like image 855
zoo Avatar asked Aug 10 '11 20:08

zoo


3 Answers

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.

like image 127
Keith Thompson Avatar answered Oct 21 '22 12:10

Keith Thompson


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.

like image 22
Adam Rosenfield Avatar answered Oct 21 '22 14:10

Adam Rosenfield


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

like image 44
Vinicius Kamakura Avatar answered Oct 21 '22 14:10

Vinicius Kamakura