C ++ cout overwrites itself during loop

The cout statement in this for loop:

for (vector<Student>::iterator qw = students.begin(); qw != students.end(); ++qw){ Student a = *qw; name = a.getName(); regno = a.getRegNo(); std::cout << "Name: "<< name << " Reg Number: " << regno << endl; } 

It creates some kind of odd behavior, what cout should print looks something like this:

Name: Mike Sanderson Reg Number: 10101

However, he does print it out:

Register Number: 10101on

It seems to me that after the second part of the cout statement, it returns to the beginning of the line and overwrites itself, but why? I hope you guys can help me, and if you need more information let me know!

+6
source share
1 answer

This is a carriage return (i.e., \r in a string literal). I assume that the name string has \r at the end of it. You need to find out how he got there and delete it.

I assume that you may have read the names from a file, and this file was created on Windows, which by default ends the lines \r\n . C ++ usually handles the conversion between line endings for you when reading from a text file, but if you are reading the file as a binary and using \n as a delimiter, you will have this problem. \r will read as if it were part of a string.

+15
source

All Articles