从cin读入结构数组时终止输入
Terminating input when reading into struct array from cin
我是一个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;
}
修复挂起的原因是,当读取字符串失败时,流仍然处于错误状态。以前,你总是在返回之前清理州内的一切。
相关文章:
- 在输入句子时终止 std::out_of_range
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 代码在执行之前终止,并且没有从用户那里获取输入
- 使用终止程序的指针在数组中输入字符串
- 程序在终止循环后不接收输入
- 如何用字符终止整数输入循环?
- 当我输入非整数值时,我的二次方程代码终止,如何让它正确循环?
- 程序终止,状态为 -1073741510 在 for 循环的中间,将输入分配给二维数组
- 程序终止,而不是继续整数输入验证循环
- 如何在C++中终止具有键盘输入的侦听 TCP 服务器
- 如何在C++中使用 if 语句终止向量输入
- (C++) 学习向量 - 编码/输入流终止/比较向量的问题
- 当用户输入 -1 时,它应该终止
- 如何将键盘输入终止
- C++循环未终止时的输入验证
- C++输入超过 11 个整数时程序终止
- cin函数是否添加了在输入结束时终止的null
- 如何在Mac上的Clion中使用ctrl+D终止输入
- 用户的空终止输入
- 从cin读入结构数组时终止输入