c++loopswhile-loopcinindefinite

Basic input £ Indefinite looping


This is a very basic program I want to run. The user is asked to choose between a choice of three variant programs, which appear later individually in the code.

I want to only accept integer inputs, with values 1,2,3,4, and 5 for example. For some reason, the current program is only accepting the 1 input, and the while loop repeats indefinitely for a non-integer input.

Can anyone spots these two problems, and suggest some fixes for me? Thanks in advance.

Code:

#include <iostream>

using namespace std;

int main() {
    int programversion;
    cout << "Which program version would you like to run? Basic [1], advanced [2], or advanced-variant [3]?\n";
    cin >> programversion;

    while (programversion != (1||2||3))
    {
        cout << "That is not a correct input integer - please choose [1], [2] or [3]\n";
        cin >> programversion;
    }

    if (programversion == 1)
    {
        cout << "You chose option 1.\n";
    }

    if (programversion == 2)
    {
        cout << "You chose option 2.\n";
    }

    if (programversion == 3)
    {
        cout << "You chose option 3.\n";
    }

    return 0;    
}

Solution

  • Your condition should be

    while ( programversion < 1 || programversion > 3 )
    {
        ...
    }
    

    The reason your while loop keeps running is because your current condition simply always evaluates to true and the loop never breaks (except when you type 1). 1||2||3 simply evaluates to 1 which is the only condition your code is correctly handling. If you want to test independent conditions, you have to actually write code to test those conditions individually. Either use my above code snippet (which checks if programversion is in the range of 1 and 3) or use multiple checks within the while expression to test each acceptable value independently. For example:

    while ( programversion != 1 && programversion != 2 && ... )
    {
        ...
    }