lundi 27 juin 2016

How to check if the input taken by the user doesn't contain decimal?

I am a newbie to C++. I have a situation where the input integer is taken from the user. However, I need to check if the user enters a decimal value. How do I check this?

I have tried cin.good(), cin.fail() but they are detecting only non-digit entries and not decimal numbers. Any help would be appreciated.

#include <iostream>

int main()
{
  using namespace std;
  int x;
  cout << "Enter an integer: " << endl;
  cin >> x;

  if (cin.good()) {
    cout << "input is an integer" << endl;
  }
  else 
    cout << "input is not an integer" << endl;
}

Here's my output:

1.

Enter an integer: 
1.2
input is an integer

2.

Enter an integer: 
a
input is not an integer

Aucun commentaire:

Enregistrer un commentaire