c++ - if(cin) 的目的?

标签 c++ c++11

我在这里寻求一些帮助来理解加速 C++ 中提出的一些概念。这是我遇到问题的地方。

vector<Student_info> students;  //Student_info is a structure we made
Student_info record;
string::size_type maxlen = 0;


// read and store all the records, and find the length of the longest name
while (read(cin, record)) { //Here is where I find hard to follow
maxlen = max(maxlen, record.name.size());
students.push_back(record);
}

read()的定义:

istream& read(istream& is, Student_info& s)
{
// read and store the student's name and midterm and final exam grades
is >> s.name >> s.midterm >> s.final;
read_hw(is, s.homework); // read and store all the student's homework grades
return is;
}

read_hw()的定义:

// read homework grades from an input stream into a vector<double>
istream& read_hw(istream& in, vector<double>& hw)
{
if (in) {
// get rid of previous contents
hw.clear() ;
// read homework grades
double x;
while (in >> x)
hw.push_back(x);
// clear the stream so that input will work for the next student
in.clear();
}
return in;
}

目前我的理解是,当我们调用:while (read(cin,record)) 时,我们要求一个字符串:record.name,并且两个 double 值:record.midtermrecord.final。在我们的用户输入该数据后,我们将进入我们的 read_hw() 函数,我们将在其中清除 vector 中可能存在的任何先前元素。然后我们将一系列值输入并记录到一个名为 record.homework 的家庭作业成绩 vector 中。我想我明白了这么多。如果没有,请告诉我。

我不明白我们的函数如何知道何时返回,并因此返回到我们的第一个 while 循环。编辑:啊,用户必须发出两次文件结束通知才能结束程序。所以我想我回答了我自己的问题......但是有人能够在我们的 read_hw() 函数中解释 if(in) 的目的吗,那将是非常有帮助。它将是if(cin),那么这是在等待我们的用户输入数据吗?还是 if(cin) 自动为真? (为什么?)

最佳答案

No if(cin) 不会等待 - 它会检查错误。只有运算符 >> 等待输入。在这种情况下,while(in >> x) 执行读取和等待。它在 while 循环条件内的原因是因为在 in >> x 完成后它返回对 in 的引用,它被隐式转换为 bool,用于发出错误信号,如 如果(cin)

在这两种情况下,如果没有错误,cin 将为真,如果有错误,则为假。

This可以更好地了解正在发生的事情,但可能并不欢迎。基本上,无论何时将 istream 视为 bool 值,如果没有错误则为 true,如果有错误则为 false。

基本上,istream(称之为 foo)到 bool 的转换总是 !foo.fail()。所以它与 fail() 相反。这意味着有两种方法可以实现(直接来自表 here :

  1. I/O 操作逻辑错误(读取错误类型等)
  2. I/O 操作读/写错误(不可预测的东西)

所以文件末尾根本没有被覆盖。必须使用 eof() 或类似方法进行检查。

如果 istream 结果为假,您可以使用 bad() 区分 1 和 2。如果 bad 为真则为情况 2,如果 bad() 为假则为情况 1。(还有其他方法,请查看 rdstate())

关于c++ - if(cin) 的目的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20961994/

相关文章:

c++ - 如何更改makefile中g++的版本

直接使用流缓冲区时出现 C++ 错误? : operator

c++ - OpenCV 具有与 Matlab 不同的 RGB 值?

c++ - 在 C 和 C++ 中, "#"是什么意思?

java - 学习 C/C++ 和 Java

c++ - 具有三元的简单 C++11 constexpr 阶乘超出了最大模板深度

c++ - shared_ptr 完全在栈上

c++ - 无法使用大括号为 C++ 对赋值

c++ - C++中map []和map.at之间的区别?

C++ - 对于指向对象的指针 vector ,重新分配是否会导致删除和复制对象?