c++ - 如何将文件中的数据读取到结构中?

标签 c++

我有一个文本文件,我想读入一个结构。

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/

相关文章:

c++ - 如何使用 C++ 返回一个抽象类

c++ - 无法将指针添加到类指针 vector 数组

c++ - 乘以 1.0 和 int 到浮点转换的精度

c++ - 是否有 std::shared_ptr 的非原子等价物?为什么 <memory> 中没有一个?

c++ - 将指针分配给指针数组中的索引

c++ - 尽管有 dllimport,但在两个 DLL 中导出的数据符号

C++ 异常返回类型为什么是 char*

C++ Forward 声明一个类?

c++ - 虚拟析构函数 : is it required in base class if base class allocated memory dynamically?

c++ - 如果共享内存的指针为空,则将其内容设置为空 c++