Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to check if the input is Integer or double. My problem is that when I inter 1.00 (which is double) my result is integer. How I can write app that distinguish between ( 1.00 and 1 ) ??

What I have tried:

int main()
{

double a;
cin >> a;
if ( floor(a) == ceil(a) )
	cout << "Integer";
else
	cout << "Double";

    return 0;
}
Posted
Updated 25-Mar-19 8:22am

Check the string Luke, check the string!
(search for the dot)

You might also use std::strtol[^] providing (and the checking) the str_end parameter.
 
Share this answer
 
v2
The only way to tell is to read it as a string instead of a double, and manually parse that. Once you have read it into a double, there is no way to tell what the user actually entered.
 
Share this answer
 
Comments
Member 14195442 25-Mar-19 9:43am    
I am required to read as double not a string
Dave Kreskowiak 25-Mar-19 10:53am    
There's no way to do that. Once you parse the string as a double, "1" and "1.00" are identical as far as the content of your a variable.

If you insist on only using a single variable of type double, the only way to tell the difference is to examine the string that was entered at the console and look for the decimal separator before you try to parse the string as a double.
You can use sscanf to make the value a string, and then evaluate the string. Google is your friend.
 
Share this answer
 
Comments
Member 14195442 25-Mar-19 9:44am    
so there is no direct way to determine if it is integer or double?
#realJSOP 25-Mar-19 11:45am    
Not in c++. Of course, you could write function to do it so you don't have to deal directly with the ugly bits.
If the user enters 2 or 2.0 the resulting value is the same. There is no way to determine what was actually typed.
 
Share this answer
 
You must fetch the input as string and THAN convert.

You may also search that string for a "."character/substring!!! :-O
 
Share this answer
 
Comments
Richard Deeming 26-Mar-19 15:56pm    
* "THEN" convert. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900