C++ cout overwriting itself while in for loop

冷暖自知 提交于 2019-12-04 03:17:54

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/14295420/c-cout-overwriting-itself-while-in-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!