Is their a way I can check if a variable contains a float or integer? I can't find a specific function which does so. Thanks.
Printable View
Is their a way I can check if a variable contains a float or integer? I can't find a specific function which does so. Thanks.
Do you mean a string representation of a number? I'll assume you do.
You can just try and apply atoi() and atof() to the strings, and if they can't be converted to int or float the return value of the functions will be 0. If the return value is any other number you know it successfully converted it, which means it must be the correct type.
You could also use isdigit, but this only accepts a single character as argument. You could test the first character of a string however...
isdigit(*str) or isdigit(str[0])
you can define a macro:
#define isinteger(x) ((x)==((int)(x)))
and use it like this:
int a=2;
float b=2.0, c=2.5;
if isinteger(a) cout << "a is integer\n";
if isinteger(b) cout << "b is integer\n";
if isinteger(c) cout << "c is integer\n";
All I want to do is say
Code:cout<<"Enter a number";
cin >> x;
//do something here to check if its a float.
Sorted :)Code:float x;
cout << "Enter a number: ";
cin >> x;
You could use my FloatPart Function :-D
If its a float, it should return 0.0PHP Code:inline double FloatPart(double f)
{
return(f-(int)f);
}
I have been having some problems with this lately... So use it at your own risk