I'm suffering a problem when trying to read test scores from a text file I entered earlier in my program. The problem is it says my variables are undefined but I think I have them defined. The writing part of the program using "ofstream" worked perfectly and gave me the output formatted in a text file.
1001 21 22 23 24
1002 25 26 27 28
1003 29 30 31 32
My goal has the following guidelines: 2. Read the data from your file. a. Use nested loops. b. The outer loop will be a “while” loop and the inner loop will be a “for” loop (4 quizzes).
Here's my code below. Hopefully someone can see where I'm going wrong and point me in the right direction:
#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;
}
Thanks for taking the time to help me by looking at this.
You are making a very trivial mistake:-
You first while loop is:-
while (studentCount <= 3)
After this your second while loop is
while (studentCount <= 3)
Since studentCount is already 4 it won't enter into this loop.
You need to re-initialise studentCount for second loop :-
studentCount = 1;
while (studentCount <= 3)