从cin读入结构数组时终止输入

Terminating input when reading into struct array from cin

本文关键字:终止 输入 数组 结构 cin      更新时间:2023-10-16

我是一个c++初学者。我想写一个简单的程序来创建student_info的记录。我创建了一个包含成员变量name和家庭作业成绩向量的structs数组。我希望从终端输入cin读入structs数组。请找到下面我的尝试这样做。我感到困惑的是如何在运行程序时终止/退出程序中的读循环。我需要继续阅读名字和一堆家庭作业成绩,形成一个单一的记录。如果我删除is.clear(),那么它只得到一条记录,当我输入下一个学生的名字时,程序退出。

我将非常感谢任何建议。

#include <cstdlib>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
struct student_info{
  string name;
  vector<double> hw_grades;
};
istream& read_single_record (istream& is, student_info& s){
  is>>s.name;
  double x;
  while(is>>x)
  {
     s.hw_grades.push_back(x);
  }
  is.clear();
  return is;}
int main() {
  //read data into an array of student info
  vector<student_info> vec_st_info;
  student_info x;
  while(read_single_record(cin,x))
  {
    vec_st_info.push_back(x);
  }             
  return 0;
  }

程序的示例输入将是

John
88
98
89
67
Sam
78
90
Tom
89
90
76

名称后面跟着一系列作业成绩,每个成绩都有一个"返回"键。作业成绩的数量也不固定

这应该通过在读取name失败时返回来修复:

istream& read_single_record (istream& is, student_info& s)
{
  if( !(is>>s.name) ) return is;
  double x;
  while( is>>x )
  {
     s.hw_grades.push_back(x);
  }
  is.clear();
  return is;
}

修复挂起的原因是,当读取字符串失败时,流仍然处于错误状态。以前,你总是在返回之前清理州内的一切。