C ++ cout在for循环中覆盖自身 [英] C++ cout overwriting itself while in for loop

查看:124
本文介绍了C ++ cout在for循环中覆盖自身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此for循环中的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;
}

正在创建一些奇怪的行为,cout应该打印的内容是这样的:

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


名称:Mike Sanderson Reg号:10101

Name: Mike Sanderson Reg Number: 10101

但是实际打印出来的是:

However which it actually prints out it:


注册号:10101on

Reg Number: 10101on

在我看来,在cout语句的第二部分之后,它又回到了行的开头并覆盖了自己,但是为什么呢?
希望你们能帮助我,如果您需要更多信息,请告诉我!

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!

推荐答案

这就是运输工具返回字符会(即字符串文字中的 \r )。我假设 name 字符串的末尾有一个 \r 。您需要弄清楚它是如何到达那里并将其删除的。

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.

我猜想您也许是从文件中读取名称的,并且该文件是在Windows,默认情况下以 \r\n 结尾。从文本文件读取时,C ++通常会为您处理行尾之间的转换,但是如果您将文件读取为二进制文件并使用 \n 作为定界符,您将遇到此问题。 \r 将被视为行的一部分。

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.

这篇关于C ++ cout在for循环中覆盖自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆