c++ - Cin 坚持输入并错误读取

标签 c++ struct cin accelerated-c++

struct Student_info {
std::string name;
double midterm,final;
std::vector<double> homework;
}; 

我正在使用 Accelerated C++ 编写一个 C++ 程序,该程序使用上述结构来定义单个学生。目标是存储和计算多个学生的成绩。该程序应该以名称、两个测试分数和一些未知数量的家庭作业成绩的形式从标准输入中获取输入。这些值都被加载到一个结构中,然后该结构被添加到 Student_info 的 vector 中。执行此操作的代码如下。

int main(){
  std::vector<Student_info> students;
  Student_info record;
  std::string::size_type maxlen = 0;

  while(read(std::cin,record)){
    maxlen = std::max(maxlen,record.name.size());
    students.push_back(record);
  }
}

std::istream& read(std::istream& is, Student_info& student){
  std::cout << "Enter your name, midterm, and final grade: ";
  is >> student.name >> student.midterm >> student.final;
  std::cout << student.name << "   "<< student.midterm << "   " << student.final; 
  read_hw(is,student.homework);
  return is;
}

std::istream& read_hw(std::istream& in,std::vector<double>& hw){
  if(in){
    hw.clear();
    double x;
    while(in>>x){
      hw.push_back(x);
    }
    in.clear();
    in.ignore(std::numeric_limits<std::streamsize>::max());
  }
  return in;
}

但是输入没有正确读取。输入

Sam 90 88 90 88 89 \eof Jack 86 84 85 80 82 \eof

给予:

student.name = Sam
student.midterm = 90.
student.final = 88.
student.homework = [90,88,89]

student.name = \eof
student.midterm = 0
student.final = 88 
student.homework 

最后一个学生不适合该结构,因此读取失败并且 while 循环结束,并且 Jack 永远不会被添加到 vector 中。

最佳答案

read_hw 中,您正在阅读 homework 直到流关闭。

第一个 \eof 字符永久关闭标准输入。

=> 其他学生无法从封闭的输入流中输入。

你必须找到另一种方法来结束 homework 输入,例如一个空行。

关于c++ - Cin 坚持输入并错误读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39430567/

相关文章:

c++ - 澄清 C++ 中 cin 的基本行为

c++ - 使用 C++ 中的嵌入式 Mongoose 服务器执行典型的服务器任务

c++ - 确定 p 的第 n 个正根的程序

c++ - 公共(public)访问声明不影响成员函数指针?

c# - 为什么 Awaiters (async/await) 是结构体而不是类?可以使用类吗?

c++ - Cin 执行不工作(program.exe < filewithdata.txt)

c++ - 如何将整数数组从 Tcl 传递到 C++?

c++ - C++结构中的位字段声明

ios - 是否有可能创建对结构数组元素的引用?

c++ - cin.getline() 跳过