Manuel Pap
Manuel Pap

Reputation: 1389

While loop never ending message

I want to test the input if it is double but the message that I wrote to pop up if the input is not double never stops to show up. Although when I turn the double into string everything its OK. Please help. I can't figure out what I have to do.

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int main(){
    double x;
    cout<<"Enter Number.\n";
    while (!(cin>>x)){
        cout<<"please only numbers.\n";
        cin >>x;

    }
    return 0;
}

Upvotes: 1

Views: 177

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129314

You need to use cin.ignore(1000, '\n'); to clear the input. You will also need to use cin.clear(); to remove the "failed" bit, so that the next input can succeed.

Upvotes: 1

Related Questions