Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ cout overwriting itself while in for loop

Tags:

c++

cout

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;
}

Is creating some odd behavior, what the cout should print is something like this:

Name: Mike Sanderson Reg Number: 10101

However which it actually prints out it:

Reg Number: 10101on

It would seem to me that after the second part of the cout statement it is going back to the start of the line and overwriting itself, but why? Hope you guys can help me and if you need more info let me know!

like image 451
Zac Powell Avatar asked Jan 12 '13 16:01

Zac Powell


1 Answers

This is what the carriage return character does (that is, \r in a string literal). I assume name string has an \r at the end of it. You'll need to figure out how it got there and remove it.

I'm guessing that perhaps you read the names from a file, and that file was created on Windows, which ends lines with \r\n by default. C++ will usually handle the conversion between line endings for you when reading from a text file, but if you're reading the file as a binary file and using \n as a delimiter, you'll have this problem. The \r will be read as though it were part of the line.

like image 156
Joseph Mansfield Avatar answered Oct 17 '22 07:10

Joseph Mansfield