Reputation: 5648
I have a int var; and using cin, but how to check if user input a float or give me a solution for this problem?
Upvotes: 0
Views: 3477
Reputation: 93476
Possibly the simplest way is to accept a float/double, cast it to an int, then test to see if the conversion modified the value.
int i ;
float f ;
std::cout << "Input: " ;
std::cin >> f ;
i = static_cast<int>(f) ;
if( static_cast<float>(i) != f )
{
std::cout << "Not an integer" ;
}
else
{
std::cout << "An integer" ;
}
Note that this will fail for large integers (most values greater than 6 digits) that cannot be exactly represented as floating point but the working range may well suit your needs.
Upvotes: 1
Reputation:
There is no easy way of doing this. Input via the >> operator
is really not intended for interaction with humans who may enter the wrong thing. You will have to read the input as a string and then check it using a function like strtol, or your own hand-rolled code.
Here's an outline of an approach using strtol:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
bool GetInt( istream & is, int & n ) {
string line;
if ( ! getline( is, line ) ) {
return false;
}
char * ep;
n = strtol( line.c_str(), & ep, 10 );
return * ep == 0;
}
int main() {
int n;
while(1) {
cout << "enter an int: ";
if ( GetInt( cin, n ) ) {
cout << "integer" << endl;
}
else {
cout << "not an integer" << endl;
}
}
}
Upvotes: 2
Reputation: 99585
You could use temporary string and boost::lexical_cast
to convert it to an integral or floating point variable as follows:
#include <iostream>
#include <boost/lexical_cast.hpp>
int main()
{
using namespace std;
string buf;
cin >> buf;
bool int_ok = false, float_ok = false;
try {
int x = boost::lexical_cast<int>( buf );
int_ok = true;
} catch ( boost::bad_lexical_cast e ) { int_ok = false; }
if ( !int_ok ) {
try {
float x = boost::lexical_cast<float>( buf );
float_ok = true;
} catch ( boost::bad_lexical_cast e ) { float_ok = false; }
}
return 0;
}
There is could be a better solution depending on what are you trying to achieve.
Upvotes: 0
Reputation: 212979
Read the variable into a temporary string, parse it to see if contains .
, ,
, E
, e
, or other non-integer characters, then convert it to int if it's valid.
Alternatively just read the value into a float and convert this to an int (with rounding or truncation as appropriate).
Upvotes: 1