Runtime error...?

I get the message "This application has requested the Runtime to terminate it in an unusual way" after trying to run this code. It happens after the first user inputs their grades then presses q. I know the code is pretty crap but I'm more concerned about the error message at the moment.

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
#include <iostream>
#include <ios>
#include <string>
#include <vector>
using namespace std;

int main()
{
    cout << "Student No. 1 please enter your name: ";
    string name1;
    cin >> name1;

    cout << "Student No. 2 please enter your name: ";
    string name2;
    cin >> name2;

    cout << name1 << ", please enter your grades. When you have finished, press 'q' to quit." << endl;

    vector<double> grades;
    double x;
    double sum1 = 0, sum2 = 0;

    while(cin >> x)
    {
        grades.push_back(x);
        sum1 += x;
    }

    vector<double>::size_type vec_sz1 = grades.size();
    if(vec_sz1 == 0)
    {
      cout << "Cannot divide by 0";
      return 1;
    }

    cout << name2 << ", please enter your grades. When you have finished, press 'q' to quit." << endl;

    double y;
    cin >> y;
    while(y)
    {
        grades.push_back(y);
        sum2 += y;
        cin >> y;
    }

    vector<double>::size_type vec_sz2 = grades.size();
    vec_sz2 -= vec_sz1;


    double average_name1 = sum1 / vec_sz1;
    cout << name1 << ", your average mark is " << average_name1;

    double average_name2 = sum2 / vec_sz2;
    cout << name2 << ", your average marks is " << average_name2;

    return 0;
}
When you enter 'q' to end first lot of entries cin goes into a fail state because it can't convert 'q' to a number.

This means line 39 cin >> y; is not performed, y remains its unitialised value which is unlikely to be 0.

The cin>>y in the while loop has no effect either so y is never changed from its original value.

This means you have an infinite loop which places many many values into the vector taking up too much memory.

Look up clear() (to reset cin) and ignore() (to get rid of the characters remaining in the input buffer when cin failed) in istreams in the reference.

Last edited on
Topic archived. No new replies allowed.