This is the correct behavior of getchar
. While scanf
's %d
format specifier converts a sequence of digits to a decimal number, with getchar
you need to do it yourself.
In order to do that, you need to know three things:
- When the sequence of digits ends,
- How to convert an ASCII code of a digit to a number, and
- How to combine multiple digits into a single number.
Here are the answers:
You can decide to end the character input when the value returned by getchar
is not a digit. You can use the isdigit
function for that (include <ctype.h>
header to use it).
You can convert a single digit character to its corresponding numeric value by subtracting the code of zero (i.e. '0'
) from the value returned by getchar
You can combine multiple digits into a number by starting the partial result at zero, and then multiplying it by ten, and adding the value of the next digit to it.
int num = 0;
for (;;) {
int ch = getchar();
if (!isdigit(ch)) break;
num = 10 * num + (ch - '0');
}