rectangletangle
rectangletangle

Reputation: 53051

Weird outputs with simple Arithmetic C++

If I give this program a string as in input it gives me some very strange outputs. How do I go about handling this? I'd like it to simply state that there was an error on the consul.

#include <cstdlib> 
#include <iostream>

using namespace std;

int main() 

{ 
    cout << endl;
    cout << "Homework (out of 70 pts):  " ;
    int HW ;
    cin >> HW ;

    cout << "Midterm (out of 100 pts):  " ;
    int MT ;
    cin >> MT ;

    cout << "Final (out of 100 pts):    " ;
    int F ;
    cin >> F ;
    cout << endl;

    int S;
    S = HW + MT + F;



    cout << "Score:     " << S << endl;
    cout << endl; 

    system("pause");
}

Upvotes: 0

Views: 142

Answers (1)

casablanca
casablanca

Reputation: 70721

When you enter a value that cin isn't expecting, such as a string instead of a number, nothing will be read into your variable and cin will set an error flag that will prevent any further input. See my answer to another question on the very same topic.

Upvotes: 4

Related Questions