【问题标题】:Cin holding onto input and reading incorrectlyCin 坚持输入并错误读取
【发布时间】:2016-09-10 21:05:54
【问题描述】:
struct Student_info {
std::string name;
double midterm,final;
std::vector<double> homework;
}; 

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

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 永远不会被添加到向量中。

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 期待投反对票,因为我回答了一个关于 Students 的问题。每次都是运气不好:)
    猜你喜欢
    • 2023-02-21
    • 2013-07-31
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多