Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does << operator cut off characters with cout?

I am using std::getline in a while loop and printing the output with cout, I find that the beginnings of my line are being cut off when I am printing:

works as expected:

std::string line;
while(std::getline(csv, line)) {
 std::cout << line << std::endl
}

doesn't work as expected, cuts the first two characters out of my line

std::string line;
while(std::getline(csv, line)) {
 std::cout << line << "  " << std::endl
}

I've never noticed this behaviour before, why is it happening now?

like image 475
user2089851 Avatar asked Nov 13 '22 10:11

user2089851


1 Answers

This is what seems to be happening:
The characters at he the end of your line string contain carriage return character. In case your string was Hello World, printing it along with a carriage return would cause the cursor to go back at the H character. Which means when you start printing anything after that, it will overwrite your old string.
To avoid this you may want to print endl before anything else.

like image 161
atoMerz Avatar answered Nov 15 '22 07:11

atoMerz