1

Say I have a float variable called "varFloat" and I use cin to allow the user to input a number, how can I prevent the user from entering a letter?

I have a calculator program that breaks if a letter is entered instead of a number.

        cout << "Enter num1: ";
        cin >> num1;
        cin.ignore(); 

        do
        {
            //Select function
            cout << "Enter a function ('+' '-' '*' '/'):";
            getline(cin, function);

            if (function == "+" || function == "-" || function == "*" || function == "/")
            {
                break;
            }
            else
            {
                cout << function << " IS AN INVALID FUNCTION" << endl;
            }
        } while (function != "+" || function != "-" || function != "*" || function != "/");

If a letter is entered for num1, the program seems to skip the getline and prints " IS AN INVALID FUNCTION" endlessly.

1 Answers1

0

how can I prevent the user from entering a letter?

Code cannot. There is no magic arm to slap the user's hand as an attempt to enter A happens.

Instead, form a helper function, not simply cin >> num1;, to accept a line of input, parse it for correctness and report results. There are 3 results: input is acceptable, input is not acceptable yet cin is still open, input is not acceptable and cin is closed.

Perhaps expand the helper function to discard unacceptable input and re-prompt when cin is still open.

For float, I do this in C with code such as this which employs strtof() to parse and provide an end-of-parsing location.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256