我正在分配作业,以将学生姓名和他们的成绩分配到一个数组中,并找到平均成绩。我似乎无法在while循环后显示任何cout语句。我将头撞在墙上已经有一段时间了,所以任何帮助都会很棒。可能有些明显的东西我正在丢失。
#include <iostream>
#include <fstream>
int main()
{
using namespace std;
//Variables
ifstream inFile;
ofstream outFile;
inFile.open("data7.txt");
outFile.open("Results.txt");
int quantity = 0;
int sum = 0;
int x = 0;
double avg = 0;
double grade[MAX];
double gradeInput;
string name[MAX];
string nameInput;
//Checks if file is found
if (!inFile)
{
cout << "Error finding input file\n";
}
while (!inFile.eof())
{
x++;
getline(inFile, nameInput);
inFile >> gradeInput;
name[x] = nameInput;
grade[x] = gradeInput;
}
for (int i = 0; x > i;)
{
i++;
inFile >> sum;
avg = avg + sum;
avg = avg / i;
}
cout << "Enter quantity of grades to be processed (0 - , " << x << ", ):";
cin >> quantity;
我改变了从文件中获取值的方式(从getline()到operator >>),而不是计算平均值的方式(而且,在计算平均值之前,请问我有多少年级考虑在内),这就是结果:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
//Variables
int MAX = 100;
ifstream inFile;
ofstream outFile;
inFile.open("data7.txt");
outFile.open("Results.txt");
int quantity = 0;
int sum = 0;
int x = 0;
double avg = 0;
double grade[MAX];
double gradeInput;
string name[MAX];
string nameInput;
//Input
//Calculations
//Checks if file is found
if (!inFile) {
cout << "Error finding input file\n";
}
while (inFile >> nameInput) {
x++;
inFile>> nameInput;
inFile >> gradeInput;
name[x] = nameInput;
grade[x] = gradeInput;
cout<<"name: "<<name[x]<<" with a grade: "<<grade[x]<<endl;
}
cout << "Enter quantity of grades to be precoessed(0 - , " << x << ", ):";
cin >> quantity;
for (int i = 0; quantity > i; i++) {
avg = avg + grade[i];
}
cout<<endl<<"Avg: "<<avg / quantity<<endl;
}
带有data7.txt,例如:
a 3
b 10
c 20
d 10
e 10
好吧,我发现在while循环中使用inFile.eof()会以某种方式干扰事物,并且一旦我将代码更改为],cout语句就可以工作了>]
while (inFile)
{
x++;
getline(inFile, nameInput);
inFile >> gradeInput;
name[x] = nameInput;
grade[x] = gradeInput;
if(inFile.eof())
{
break;
}
}