1

I would like to validate if the user input is Float or not, the program checks if the input was float and prints "Number is fine" else it prints "Number is not fine" and it continue the loop without taking the failed attempt in consideration of the loop, in other way it gives him another try to enter a float number instead.

The problem is that the program goes on infinity loop once the user enter a "Character". what i actually want it to do is just printing "Number isn't fine" then continue.

Can anybody tell me why does this happen, also please consider not to use any additional libraries.

#include <iostream>
#include <windows.h>


using namespace std;
int main()
{
    int x;
    float num;
    cout << "Please enter the amount of numbers you wish to enter" << endl;
    cin >>  x;

    cout << "Please enter the numbers" << endl;
    for(int i=0; i < x;) {
        if(!(cin >> num)) {
            cout << "Number isn't fine" << endl;
            continue;
        }
        cout << "Number is fine" << endl;
        ++i;
    }
    system("pause");
}

@Steve your solution worked by using both cin.clear() and cin.ignore

@AndyG Thanks for your help but unfortunately im limited to the simplest way.

Here is the final code if somebody wanted to know how it looks in the future.

#include <iostream>
#include <windows.h>

using namespace std;
int main()
{
    int x;
    float num;
    cout << "Please enter the size of numbers" << endl;
    cin >>  x;

    cout << "Please enter the numbers" << endl;
    for(int i=0; i < x;) {
        if(!(cin >> num)) {
            cin.clear();
            cin.ignore();
            cout << "not a float number" << endl;
            continue;
        }
        cout << "Number is fine" << endl;
        ++i;
    }
    system("pause");
}

1 Answer 1

2

If cin >> num fails to read a number then the stream is put into the failed state (that is, the failbit is set), and it doesn't read past the character that caused it to fail. You never do anything to clear() the fail state or to ignore() the bad data, so you loop forever.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.