PDA

View Full Version : [SOLVED] Simple C++ question



jualin
October 28th, 2009, 01:44 AM
I am writing this program and one part of it is integer verification. I would like to know how can I check if the input value was an integer.
The programming language is C++.
Any ideas are welcome, thank you!

Bachstelze
October 28th, 2009, 01:48 AM
Psudocode:


for char in string
if !isdigit(char)
return false
return true

jualin
October 28th, 2009, 01:49 AM
Wouldn't that check if the number is "numeric". How can you check if the number is an "integer" and not a "double"?
Thank you

Bachstelze
October 28th, 2009, 01:50 AM
Wouldn't that check if the number is "numeric". How can you check if the number is an "integer" and not a "double"?
Thank you

Because a double would contain a decimal separator, which is not a digit.

Frak
October 28th, 2009, 01:54 AM
First thing that came to mind was to cast the value into another type, then compare the entered value against the casted value. If they're equal, it was an integer, if it wasn't, then it wasn't.

I go the long way for 99% of the stuff I do, because I'm always too lazy to check docs or anything of the sort.

nmccrina
October 28th, 2009, 02:05 AM
Bachstelze method is what I would use.

Also, how did a forums staff member comment on this and not move it to Programming Talk??? lol

jualin
October 28th, 2009, 02:07 AM
Because a double would contain a decimal separator, which is not a digit.

Thank you very much!
You were right it works just great.


First thing that came to mind was to cast the value into another type, then compare the entered value against the casted value. If they're equal, it was an integer, if it wasn't, then it wasn't.

I go the long way for 99% of the stuff I do, because I'm always too lazy to check docs or anything of the sort.

That was the first thing I had in mind as well. But I wasn't able to make it work. Another thing I tried which worked was using the fmod built in function, but I needed to have a temporary double variable which made the code messier.

Thank you both for the quick help!

Hyporeal
October 28th, 2009, 02:14 AM
You might consider something like this:


istringstream in(str);
int value;

in >> value;

if (in.fail()) {
cout << "It wasn't an integer!" << endl;
} else {
cout << "It was an integer!" << endl;
}

Isn't this the C++ way of doing things? It'll even work with negative numbers.

jualin
October 28th, 2009, 03:28 AM
Thank you all for the suggestions.