Check numeric entry

I want to enter a number, a character at a time and check that it is (0-9) or (+) or (-). How do I go about that in C++?

Hint 1: To load a character and check if it's a number or a sign you do this:
1
2
3
4
5
6
7
8
char c;
std::cin >> c;
if (c >= '0' && c <= '9')
	//c is a digit
if (c == '-')
	//c is a minus sign
if (c == '+')
	//c is a plus sign 


Hint 2:
The algorithm goes like this.
First, you'll have a variable where you'll put your result.

For the first character you'll need to check if it's a minus sign (meaning it's negative number) or if it's a plus sign or a digit (meaning it's a positive number) and you'll need to preserve this information.

For every other digit that you read you multiply the result by 10 first and add the last digit to the result, and you repeat this until the last digit.

When you're about to return, recall whether the number is positive or negative and return result or -result accordingly.
Last edited on
@Ihatov
Thank you for your reply.
I'll have a look at this and see if I can incorporate it in a function.
I think I'm stating the obvious (but I was always taught to ask the stupid question - in case it turns out not to be stupid), this will be a string that will then have to be converted into a number?
The way you'll implement it is completely up to you.

You can read directly from the std::cin to produce a number, or you can read the characters into a string and make a function that does so.

Note if you're going to read into a string first, you don't even have to make this function yourself because there are several functions in the stdlib that will convert a string to a number for you.
Functions like atoi(), atol() or strtol().

http://www.cplusplus.com/reference/cstdlib/atoi/
http://www.cplusplus.com/reference/cstdlib/atol/
http://www.cplusplus.com/reference/cstdlib/strtol/

None has any significant advantage against the other, though the usual recommendation is to use strtol().
Topic archived. No new replies allowed.