我正在尝试从txt文件中读取文件并将其存储在结构中。它只读取第一行和第二行然后停止。我在for循环的getdata函数中遇到了问题,无法再继续了。
规格:
文字档案:
8 6 60 Nayyar, Kunal 10 8 7 10 9 10 Foxx, Redd 8 9 9 10 10 7 Lopez, George 9 6 8 9 10 10 Walters, Barbara 10 8 4 9 7 9 Chan, Jackie 9 9 8 10 10 8 Foxx, Jamie 8 4 10 9 5 7 Cole, Natalie 9 10 8 9 7 9 Liu, Lucy 9 10 3 7 8 9
第一行是学生人数,分数和最高分数 第二行是学生姓名 第三行是每个学生6分。
代码:
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
struct Work
{
int* scores;
double percent;
};
struct Student
{
string name; // student name
Work work; // scores of student
};
int* getdata();
int main()
{
Student * stuptr;
getdata();
}
int * getdata()
{
ifstream infile;
infile.open("grades.txt");
if (!infile)
{
cout << "Error opening file\n";
return 0; // fail to open, return 0
}
int num_stu, num_scor, max_sco;
infile >> num_stu >> num_scor >> max_sco;
Student * eptr = new Student[num_stu];
Student name_s[num_stu];
cout << num_stu << endl;
int * sptr = new int[num_scor];
int studentsco[num_scor];
cout << num_scor << endl;
for (int i = 0; i < num_stu; i++)
{
infile >> name_s[i].name;
for (int j = 0; j < num_scor; j++)
{
infile >> studentsco[j].work.scores;
}
cout << name_s[i].name << " ";
// cout << studentsco[j].work.scores;
/* infile >> name_s[i].name;
cout << name_s[i].name << " ";
infile >> studentsco[j].work;
cout << studentsco[j].work << " ";*/
/* for (int j = 0; j < exact; j++)
{
infile >> studentsco[j].work;
cout << studentsco[j].work << " ";
} */
}
cout << endl;
infile.close();
return 0;
}
答案 0 :(得分:0)
我不太清楚为什么原始代码不起作用,但我建议对您的程序进行以下更改:
#include <iostream>
void getdata(Student& s, int n, std::ifstream& infile)
{
std::getline(infile >> std::ws, s.name);
for (int k = 0; k < n; ++k)
{
infile >> s.work.scores[k];
}
}
int main()
{
std::ifstream infile("grades.txt");
int num_stu, num_scor, max_sco;
infile >> num_stu >> num_scor >> max_sco;
Student* students = new Student[num_stu];
for (int i = 0; i < num_stu; ++i)
{
students[i].work.scores = new int[num_scor];
getdata(students[i], num_scor, infile);
}
}