user2992251
user2992251

Reputation: 27

cin in while loop doesn't work properly (C++)

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

Answers (2)

jcm
jcm

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 gotoyou're looping twice:

  1. You enter 1.5
  2. test is 1 and you don't enter if, so cin is not cleaned up.
  3. loops again and cin immediately returns.
  4. test is 0 so enters if statement and complains.

Hope this helps

Upvotes: 1

BoBaH6eToH
BoBaH6eToH

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

Related Questions