我有一个文本文件,我想读入一个结构。
Harry;3.4;3.21;2.83;3.78
Ron;2.89;2.21;2.10;3.33
Hermione;3.65;3.78;4.0;3.89
Dumbledore;2.36;2.75;3.12;3.33
Snape;3.12;2.4;2.78;3.2
这是学生结构。
struct Student
{
string name;
double gpa[4];
double averageGPA;
};
我已经动态分配了 Student 数组,现在我想从文件中读取数据。使用 getline(infile, pointer[0].name, ';');
可以获取名字,但我无法读入数字。如果我使用 getline(infile, pointer[0].gpa[0], ';');
我会收到错误消息。我认为这是因为 double gpa[4]
不是字符串?我怎样才能读入数字数据?
最佳答案
要读取整数,请使用 operator>>
getline(infile, pointer[0].name, ';');
for (int loop = 0; loop < 4; ++loop) {
infile >> pointer[0]. gpa[loop];
// You now need to read the ';' off the input stream
// Note the last number is not followed by a ';'
}
不是上面的代码没有做任何错误检测。您应该添加它。
结构/类通常也定义自己的输入运算符。
std::istream& operator>>(std::istream& in, Student& data)
{
// do the reading in here.
return str;
}
完成后,读取 stuent
对象就很容易了。
int main()
{
Student s1;
std::cin >> s1;
}
关于c++ - 如何将文件中的数据读取到结构中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35097380/