我是编程新手,我无法从文件中读取数据并将其输入结构数组,同时要跟踪输入的每个数据:
文件将包含:
姓名、身份证号码和 GPA
Courtney Love 1234569 3.5
Bob Joe 1234570 3.0
Dave Henry 1234571 2.9
struct Student
{
string name;
int id;
float GPA;
void printStudent();
};
声明一个最多可容纳 5 个成员的 Student 类型数组:
Student a_members[5];
打开文件,读入每一行并将数据存储在数组中,跟踪读入的每个学生:
fstream file_;
file_.open ("students.txt");
if(file_.is_open())
{
while(file_.good())
{
}
}
else
{
cout << "File is not open"<< endl;
}
return 0;
我卡在了“while”条件语句上。在那之后我不知道我应该怎么做才能逐行输入文件中的数据并将其放入“结构数组”。截至目前,我觉得我已经尝试了一切!我删除了所有内容并认为最好重新开始。它变得太复杂了!也许我只是不理解这个概念。如果有人能指出我正确的方向,请这样做!谢谢!
最佳答案
你不应该使用good()
,就像你不应该使用eof()
一样。
(在任何像样的初学者级别的 Material 中都没有使用,但每个初学者都设法找到它们。然后他们想知道为什么它不起作用。)
相反,您应该依赖这样一个事实,即如果流本身处于良好状态,则它是“真实的”,并且继续阅读直到它不是。
惯用的 C++ 看起来像这样:
std::ifstream file("students.txt");
Student s;
while (file >> s.name >> s.id >> s.GPA)
{
// Process the student
}
或者,花哨的版本:
std::istream& operator>> (std::istream& is, Student& s)
{
return is >> s.name >> s.id >> s.GPA;
}
std::ifstream file("students.txt");
Student s;
while (file >> s)
{
// Process the student
}
(在您的代码中,您还需要跟踪您阅读了多少个Student
。)
关于c++ - 简易程序 : Store Data from a file into a Struct Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32407716/