Search code examples
c++infinite-loop

How to make an exit in switch case implementation with user prompt?


I've a basic computing program, in it I want that when a user wants to just quit the program in his very first input without making any calculation, the program just exits. But rather here if the user enters q for quit/exit in his first input the programs runs into an infinite loop. Is there any way to provide user with some single exit key which when entered anytime(by the user) during runtime just quits the program. The innermost while loop works fine unless the outermost loop stops working.

#include "std_lib_facilities.h"
int main() {
    double x = 0, y = 0, result = 0;
    string operation = " ";
    char op = ' ';
    cout << "\nInput (e.g. -> 5*6)\nPress q to quit.\n";
    while(1) {
        cin >> x >> op >> y;
        switch(op) {
        case '+':
            result = x + y;
            operation = "sum";
            break;
        //Other switch cases
        case 'q':
            exit(1);
        default:
            cout << "Invalid input.";
            break;
        }
        cout << "The " << operation << " of " << x << " and " << y << " is "
            << result << ".\n\n"
            << "If you have another input, press any character to continue..\n"
            << "Else press q to quit.\n";
        // exit or continue program loop
        while(cin >> op) {
            if(op=='q' || op=='Q')
                exit(1);
            else
                cout << "Provide next set of inputs.\n";
            break;
        }
    }
}

Solution

  • If the user enter q on the first try then the stream will try to read this value to x which is a double which will fail and the state of the stream will be set to fail, after that no other I/O operation will be successfully performed and the loop will run infinitely.

    You could probably check for the state of the stream just before you ask the user to continue or quit and clear the stream state if the previous operation was failed:

        if(cin.fail())//check if the previous read operation failed
            cin.clear();//clear the stream state,so the next cin will read what is in the buffer
        while(cin >> op)
          ...//your other code