5

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?

7
  • From the above example, how do you know that it is cout to blame and not that the line is actually missing the expected characters? Commented Feb 27, 2013 at 5:40
  • Because I used printf("%s\n", line.c_str()); and got the expected line. And also the text " " that I add in replaces the start of my string, Commented Feb 27, 2013 at 5:42
  • 2
    I think you may have printed carriage return which causes your " " to replace beginning of your string. Commented Feb 27, 2013 at 5:44
  • 1
    You're right, the data is from a windows machine and getline takes the carriage return but not the newline. Then I overwrite it later. Commented Feb 27, 2013 at 5:51
  • 1
    @AtoMerZ - You might wan't to put your comment about "Carriage return getting printed and then the two spaces overwriting the actual characters ..." as an answer. As this seems to be the problem as said by author in his comment above. Putting it as an answer would make this qn. more useful and well gain you some SO reputation as well :) Commented Mar 1, 2013 at 16:26

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.