Danny
Danny

Reputation: 13

How to kill off a program with cin.fail()

So I'm trying to make a condition so that if the user inputs anything besides an integer the program will terminate. Whenever I put let's say the letter A the program repeatedly outputs zero. I think its exit() thats the issue but when I substitute it I have the same problem. Advice?

#include <iostream>
#include <cctype>
#include <cstdlib>


using namespace std;
void even(int);
void odd(int);
int main()
{
    int i;
    do{
        cout << "Enter an integer" << endl;
        cin >> i;
        if(i % 2 == 0)
            even(i);
        else if (i % 2 == 1)
            odd(i);
        else if (cin.fail())
            exit (0);
    }while(!isdigit(i));

    return (0);
}
void even(int i)
{
    cout << i << endl;
}
void odd (int i)
{
    //nothing here
}

Upvotes: 1

Views: 246

Answers (2)

Paul
Paul

Reputation: 442

I suppose a little tweak in your program should solve the issue for you :

if (cin.fail())
            exit (0);
        else if(i % 2 == 0)
            even(i);
        else if (i % 2 == 1)
            odd(i);

Upvotes: 0

aschepler
aschepler

Reputation: 72271

If cin >> i fails, the variable i is not assigned. In your program, this means it still has an indeterminate value. Using an indeterminate value as in (i % 2 == 0) is undefined behavior, meaning as far as the C++ Standard is concerned, anything could happen.

On most common systems, though, the variable i will have some value, whatever was left over from the last time some register or piece of memory was used. This value will be either even or odd. So if i happens to be zero or positive, your fail check will never be reached.

You will probably want to reorder your if checks to check cin first, and only use i if the extraction was successful.

Upvotes: 2

Related Questions