Home > Net >  Input Handler not working as intended C
Input Handler not working as intended C

Time:11-30

I am trying to make a program that reads from the keyboard a number corresponding to an index of an answer for a question and returns an error message if the type of date entered is wrong.

float Handlers ::InputHandler(string Question, unsigned short int Number_of_Answers)
{

    float Answer;

    cout << Question << endl << endl;
    while (!(cin >> Answer) || Answer < 1 || Answer > Number_of_Answers || Answer - floor(Answer))
    {
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            ErrorHandler(InputErrorNumber);
        }
    }

    return Answer;
}

The program worked perfectly until I entered the value 1ddga (and other cases that respect the form 1 or 2 string, 1 and 2 are the answers that the person can choose from). After I entered the respective value, the program continues with answer 1 and then if I try to ask for an answer using the same function, it returns the error message, after the question and then asks for my input. It is as if from 1ddga it read 1, and the rest was stored somewhere, and on the next reading, this save was checked and then it continued to ask for another input.

Is there any solution? For example, can I return to that while after it has read such a value, or at least stop the error message on the next reading?

Here it asks for my input

Here I add a wrong value

and here is the case where I enter the specified value (it continued running and showed me the message on the next reading)

CodePudding user response:

It is as if from 1ddga it read 1, and the rest was stored somewhere

That's completely correct, if by 'stored somewhere' you mean that it remains in the console buffer waiting to be read next time around. This is how operator>> on an float is defined to work. It reads characters until it finds a character which cannot be part of a float, at that point it stops.

When you have precise input requirements then the only way to handle that is to do the error checking yourself. Read the input as a string, using getline for example. Then check if the input matches your expectations and then convert the string read into the value you want.

In your case, for example, you might read a string using getline, remove any leading or trailing whitespace, check if all the characters left are digits, and finally check that there is at least one digit. If all of that is true convert the string into an integer, otherwise do some kind of error handling.

  • Related