Weird error with string

My program is supposed to take in an input file of names followed by test scores. At this point I am just trying to compare the answers someone gave, with the key. What is happening is when I run the program, I get this:

Enter the name of the file where the ungraded tests are located: tests.cpp
a(A)
b(C)
c(D)
A(B)
a(C)
a(B)
d(D)
c(C)
c(C)
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string
Abort trap: 6

And I can't figure out what to do about the other test scores I need to be outputted. The problem lies in the output function at the bottom, I think. Any help would be much appreciated. Thank you.

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
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

void single_grade(string key, string first[], string last[], string answer[], double grade[]);
void output(string key, string first[], string last[], string answer[]);

int main(){
    string input_filename, first[9], last[9], answer[9], key;
    double grade[10];

    cout << "Enter the name of the file where the ungraded tests are located: ";
    cin >> input_filename;
    ifstream inp;
    inp.open(input_filename.c_str());

    
    getline(inp, key);
    for(int i=0; !inp.eof(); i++){
        
        getline(inp, first[i], ' ');
        getline(inp, last[i], ' ');
        getline(inp, answer[i]);
    }
    
    inp.close();
    output(key, first, last, answer);
    single_grade(key, first, last, answer, grade);
    
    return EXIT_SUCCESS;
}

void single_grade(string key, string first[], string last[], string answer[], double grade[]){
    double score;
    double ppts;
   for(int j = 0; j < 9; j++){
        score = 0;
        ppts = 0;
        for(int i = 0; i < answer[j].size(); i++){
            if(answer[j].at(i) == key.at(i)){
                ++score;
            }
               ++ppts;
        }
        grade[j] = (score/ppts)*100;
   }

}
void output(string key, string first[], string last[], string answer[]){


    for(int i = 0; i < 15; i++){
        cout << answer[i].at(i) << "(" << key.at(i) << ")" << endl;
    }
}
The problem is probably the loop on line 23.

You improperly check the eof. Let's say you read the last (9th) line on line 27. There is no eof. So you read the 10th (out of bounds) line on line 25. That would cause a crash.
Topic archived. No new replies allowed.