是否可以在同一个程序中使用 scanf() 和 getchar() 来获取输入?

Is it possible to use scanf() and getchar() in the same program to get input?

我正在努力完成作业,但偶然发现了一个与 scanf() 和 getchar() 相关的问题。本题需要一个代码片段作为示例,要求学生证明这两个函数都可以从输入中检索出一个字符。

然而,当我尝试将它们放在同一个程序中时,只有第一个函数是 运行 正确的。后者完全丢弃。

#include <stdio.h>

char letter;
int main()
{
    printf("I'm waiting for a character: ");
    letter = getchar();
    printf("\nNo, %c is not the character I want.\nTry again.\n\n",letter);

    printf("I'm waiting for a different character: ");
    scanf("%c",&letter);
    printf("Yes, %c is the one I'm thinking of!\n",letter);
    return(0);
}

output

我试过调换这两个函数的位置,但没有用。 有人可以帮我找到问题并提供解决方法吗?唯一的要求是程序接受两次输入,一次通过 getchar() 函数,一次通过 scanf()

第二次读取尝试只是读取白色space(行尾字符,因为您在第一个字母后按了回车键)。只需将其替换为:

scanf(" %c", &letter);

% 之前的 space 将告诉 scanf 读取下一个非白色 space 字符。