Beginner needing help with run time check failure #2

Can't seem to find what is causing the issue here so maybe someone with some experience can give me a little insight.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;

const int QUESTIONS = 10;
const int NUM_STUDENTS = 10;
const int SIZE = 30;
const double POINT_VALUE = 5;
const double MULTIPLIER = 100;

struct StudentRecords
{
	int id;
	char name[SIZE];
	string student_name;
	char answers[QUESTIONS];
	int correct_answers;
	double total_points;
	double average;
	char letter;
};

void getAnswerKey(char[]);
void getStudentInfo(StudentRecords[]);

int main()
{
	char key[QUESTIONS];
	StudentRecords student[NUM_STUDENTS];

	getAnswerKey(key);
	getStudentInfo(student);

	return 0;
}

void getAnswerKey(char key[])
{
	cout << "Enter the answer key.\n";
	for (int i = 0; i < QUESTIONS; i++)
	{
		cout << "    Answer " << i + 1 << ": ";
			cin >> key[i];
	}
}

void getStudentInfo(StudentRecords student[])
{ 
	ifstream inFile;  //Input file stream to open file and read         

	int i = 0; //index for position in array of structures
	inFile.open("student.txt"); //open file to read from 

	if (!inFile) //check to see if file is open
		cout << "\n\n**** ERROR OPENING FILE. ******\n" << endl;
	else
	{
		while (!inFile.eof()) //while not at end of file(eof)
		{
			inFile >> student[i].id; //read student id
			inFile.getline(student[i].name, SIZE, '\n');//get name
			//store in string member of structure
			student[i].student_name = student[i].name;
			for (int j = 0; j < QUESTIONS; j++)
			{
				inFile >> student[i].answers[j];   //read answers
			}
			i++;
			if (inFile.eof()) //if end—of-file, break out of loop
				break;
		}
	}
	inFile.close();
}
Looping on eof is wrong.

You make no effort to ensure that i in the loop that begins on line 61 remains within the bounds of the student array.

Lines 63 and 64 are likely to give you problems as they're written. I wouldn't be surprised if your input extraction failed prior to reaching eof, putting inFile into an error state and making your loop infinite. (google "Mixing formatted and unformatted input extraction")

Line 72/73 is redundant. Your code is functionally equivalent without those lines.
Last edited on
Topic archived. No new replies allowed.