如何在从.txt文件中读取时不重复相同的变量名
How to not repeat same variable name when reading from a .txt file
我有这个.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});
}
(我想你意识到你没有存储你计算的平均值吧?)
相关文章:
- 你能重载对象变量名本身返回的内容吗
- 在C/C++中将变量名定义为__00000001有什么好处吗
- 全局变量 多读取器 一个写入器多线程安全?
- C++变量名(可以将 main 声明为变量,但对于其他函数名称则不然)
- C++ - 声明中变量名后面的括号
- 尝试通过共享指针使用变量时读取访问冲突
- 如何使替换 c 函数的变量名成为错误?
- 是否可以创建没有变量名的变量
- fstream库,试图创建一个变量名为(c++)的文件
- 一个数组C++中的消息和变量名
- 在变量名后声明带有 () 的非内部类型与不使用变量名的行为不同。即 std::map<int,char>x(); - 这是怎么回事?
- 数组的变量名和该数组的地址有什么区别?
- 如何将变量名设置为字符串?C++
- 类中具有相同变量名的多重继承
- 编译器是否可以从全局变量中读取两次,而不是存储一个局部变量
- 如何在从.txt文件中读取时不重复相同的变量名
- 在循环中使用相同的变量名可以吗
- C++保留符号作为C变量名
- 在C++中,在给定的相同作用域内声明相同的变量名
- 为什么类名与"::"一起使用在变量名之前?