【问题标题】:Trouble with using getchar() instead of scanf()使用 getchar() 而不是 scanf() 的问题
【发布时间】:2014-05-07 18:20:19
【问题描述】:

我在做这个 C 编程练习时遇到了麻烦。我需要使用 getchar() 方法而不是 scanf()。当我使用 scanf 时,当我键入例如 7 时,一切正常。但是,当我使用 getchar() 并键入 7 时,我将得到 7 的 ASCII 代码,而不是 int 7。我该如何解决这个问题?

#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;
    }

【问题讨论】:

    标签: c scanf getchar


    【解决方案1】:

    这是getchar 的正确行为。 scanf%d 格式说明符将数字序列转换为十进制数,而 getchar 则需要您自己完成。

    为了做到这一点,你需要知道三件事:

    1. 当数字序列结束时,
    2. 如何将数字的 ASCII 码转换为数字,以及
    3. 如何将多个数字组合成一个数字。

    以下是答案:

    getchar返回的值不是一个数字时,你可以决定结束字符输入。您可以为此使用 isdigit 函数(包括 &lt;ctype.h&gt; 标头以使用它)。

    您可以通过从getchar 返回的值中减去零代码(即'0')将单个数字字符转换为其对应的数值

    您可以将多个数字组合成一个数字,方法是将部分结果从零开始,然后将其乘以 10,然后将下一个数字的值加到它上面。

    int num = 0;
    for (;;) {
        int ch = getchar();
        if (!isdigit(ch)) break;
        num = 10 * num + (ch - '0');
    }
    

    【讨论】:

    • 很好的答案。在这种情况下,我经常使用一个优雅的技巧:如果c 包含一个数字,那么c-'0' 将返回它。
    • +1。小改进:通过减去 字符 零(即'0') - 不需要是 ASCII。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多