如何在从.txt文件中读取时不重复相同的变量名

How to not repeat same variable name when reading from a .txt file

本文关键字:变量名 读取 txt 文件      更新时间:2023-10-16

我有这个.txt文件

Anna 70 79 72 78 71 73 68 74 75 70
Jason 78 89 96 91 94 95 92 88 95 92
kim 83 81 93 85 84 79 78 90 88 79
Maria 93 100 86 99 98 97 96 95 94 92
Daniel 72 60 82 64 65 63 62 61 67 64

我必须将名称和10个数字的平均值存储在一个有两个变量的结构向量中,字符串名称&int平均值。

我是这样做的:

struct Student
{
string name;
int score;
};
int main() {
string defaultPath = "lab2.txt";
ifstream inFile(defaultPath);
while (inFile.fail())
{
cout << "Fail while opening the file.n";
cout << "Please enter a different .txt name/directory: ";
getline(cin, defaultPath);
}
string name;
int score = 0, totalScore = 0, averageScore = 0;
vector<Student> studentData;
while (inFile >> name >> score >> score >> score >> score >> score >> score
>> score >> score >> score >> score)
{
totalScore += score;
averageScore = totalScore / 10;
studentData.push_back({name, score});
}
}

问题是,存储在向量from score中的是.txt文件中的最后一个分数数(70,92,79…),因为在进入代码计算平均值之前,它会一次又一次地重新分配分数。

我试着在while循环中创建另一个循环,但没有成功。。我认为唯一可行的方法是为每个数字分配一个变量名(例如score1、score2、score3…score10),但我相信还有其他更有效的方法!不知道怎么。。

除了制作10个具有不同名称的score变量外,你可以在循环中得到分数:

while (inFile >> name)
{
while (infile >> score)
{
totalScore += score;
}
averageScore = totalScore / 10;
studentData.push_back({name, score});
}

(我想你意识到你没有存储你计算的平均值吧?)