简体   繁体   中英

C++ cout overwriting itself while in for 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;
}

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM