Reputation: 27
This program should check if entered number is integer. It works fine with strings but not with doubles.
int test;
cout << "Enter the number:" << endl;
while(true) {
cin >> test;
if (!cin || test < 0) {
cout << "Wrong input, enter the number again:" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
Upvotes: 2
Views: 1051
Reputation: 2578
test
is int
. istream
>> operator is just dynamic casting to int and, then, you're losing decimal part.
Yo can just define test
as float
and cast it to int
when needed.
Edit: Answering you last edit (I didn't refresh so I missed this part), what is happening is that, without the goto
you're looping twice:
test
is 1 and you don't enter if, so cin
is not cleaned up.cin
immediately returns.test
is 0 so enters if statement and complains.Hope this helps
Upvotes: 1
Reputation: 58
Try this:
int test;
cout << "Enter the number:" << endl;
while ( true )
{
cin >> test;
if (!(test < 0 || !cin))
break;
}
cout << "Your chosen number is: " << test << endl;
Is that what you want?
Upvotes: 1