0

I'm creating a simple console application in C++ that contains a while loop that takes two integers as input. But if I enter a character that is not a integer, such as "a", the loop becomes infinite. How do I stop this?

My code is supposed to terminate upon entry of the char value '|' but it takes integers in as input and I'm not sure how to address this problem.

My code so far (trying to end a loop upon input of the char value '|'):

int main()
{

    int x = 0;
    int y = 0;
    char c = {x};
    char d = {y};

    while (c != '|')
    {
        cin >> x >> y;
        // later I will do stuff with x and y
    }

    system("pause");
    return 0;
}
Jongware
  • 22,200
  • 8
  • 54
  • 100
J.J
  • 1
  • 1
    Possible duplicate of [Checking input value is an integer](http://stackoverflow.com/questions/18728754/checking-input-value-is-an-integer) – default Jul 31 '16 at 10:46
  • This answer should be helpful: https://stackoverflow.com/questions/26285232/validating-input – Galik Jul 31 '16 at 10:59
  • Also this one: https://stackoverflow.com/questions/33037415/validating-input-with-cin – Galik Jul 31 '16 at 11:01

1 Answers1

4

You can simply add this in your while loop:

if(cin.fail()) {
    break;
}

Check also this answer, it wiil help you a lot.

Your code should be like:

int main()
{

    int x = 0;
    int y = 0;
    char c = {x};
    char d = {y};

    while (c != '|')
    {
        cin >> x >> y;
        if(cin.fail()) {
            break;
        }
        // later I will do stuff with x and y
    }

    system("pause");
    return 0;
}

Otherwise if you want not to totally break while loop then use continue instead of break

Community
  • 1
  • 1
Aleksandar Đokić
  • 2,118
  • 17
  • 35