我试图从我之前在程序中输入的文本文件中读取测试分数时遇到问题。问题是它说我的变量未定义,但我想我已经定义了它们。使用“ofstream”的程序的写作部分完美地工作,给了我一个文本文件格式化的输出。从文本文件C++中读取输入
1001 21 22 23 24
1002 25 26 27 28
1003 29 30 31 32
我的目标有以下原则: 2.从文件中读取数据。 a。使用嵌套循环。 b。外部循环将是一个“while”循环,内部循环将是一个“for”循环(4次测验)。
下面是我的代码如下。希望有人能看到我要出错的地方,并指向正确的方向:
#include <iostream>
#include <cmath>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
int numStudents, numTests = 4, studentCount = 1, count = 1, test = 1, score = 0, testCount = 1,
int stuID;
double average;
double total;
ofstream outputFile;
ifstream inputFile;
cout << fixed << setprecision(2);
//Open file scores.txt
outputFile.open("Scores.txt");
//Get the number of students
cout << "How many students? ";
cin >> numStudents;
while (studentCount <= 3)
{
cout << "Enter Student ID: ";
cin >> stuID;
outputFile << stuID << " ";
for (test = 1; test <= numTests; test++)
{
cout << "Enter grade for quiz " << test << ": ";
cin >> score;
outputFile << score << " ";
}
outputFile << endl;
studentCount++;
}
outputFile.close(); //closes Output File
inputFile.open("Scores.txt"); //opens Output File
while (studentCount <= 3)
{
for (test = 1; test <= numTests; test++)
{
inputFile >> score;
total += score;
}
average = total/numTests;
inputFile >> stuID;
cout << "The average for student " << stuID << " is " << average << endl;
studentCount++;
}
inputFile.close(); //closes Input File
system("pause");
return 0;
}
感谢您抽出宝贵时间来帮助我。
你得到编译错误或运行时错误? “它说我的变量未定义”是什么意思? – irrelephant 2014-11-02 21:20:01
除非我误解,否则您将'score'添加到'total',而不给'total'一个初始值。 – druckermanly 2014-11-02 21:20:01
如果您不明白您遇到的错误,请考虑发布错误的整个文本,而不是尝试总结它。 – 2014-11-02 21:24:28