سؤال

I'm having trouble making this exercise for C-programming. I need to use the getchar()-method instead of the scanf(). When I use the scanf, everything works perfect when I type for instance 7. However when I use the getchar() and type 7, I will get the ASCII-code of 7, not the int 7. How do I fix this?

#include <stdio.h>
    #include <stdlib.h>

    int main(void) {
        int i;

        printf("Voer een getal in:\n");
        fflush(stdout);

        i = getchar();
        //scanf("%d", &i);

        if (i > -1000 && i < +1000) {
            printf("het ingevoerde getal is: %d\n", i);
        } else {
            printf("foutieve invoer\n");
        }

        return EXIT_SUCCESS;
    }
هل كانت مفيدة؟

المحلول

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:

  1. When the sequence of digits ends,
  2. How to convert an ASCII code of a digit to a number, and
  3. 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');
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top