Reading a number

In C 'A' is an int constant used to represent the character ‘A’. The same is true for digits, of course.

If you have a variable c which contains a digit (say ‘9’) you can find the numerical value by c - '0' which in this case evaluates to 9.

If you wish to read a number (such as 124) from input using getchar(), you can do as follows. First check that the current input char you have read is a digit. Do that with the function isdigit. It returns a nonzero value if you give it a digit, such as '0' or '9'. To read a number then, you can have a variable x initially set to zero, and do:

x = x * 10 + c - '0';

Do this for each input char c you read that is a digit. If we read the digits '1', '2', and '4' in sequence, x will first be 0, then 1, then 12, and finally 124!

Note that the type of c should be int, as explained here.

Leave a Reply

Your email address will not be published. Required fields are marked *