无法使用 %c 读取 C 中的字符输入

Unable to read the char input in C using %c

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

int main()
{

    int num1;
    int num2;
    char op;

    printf("Enter the first number: ");
    scanf("%d", &num1);
    printf("Enter an operator: ");
    scanf("%c", &op);
    printf("Enter the second number: ");
    scanf("%d", &num2);

    switch(op){

        case'+':
            printf("%d", num1+num2);
            break;

        case'-':
            printf("%d", num1-num2);
            break;

        case'/':
            printf("%d", num1/num2);
            break;

        case'*':
            printf("%d", num1*num2);
            break;

        default:
            printf("Enter a valid Operator");

    }

    return 0;
}

我尝试构建一个带有用户输入的基本计算器。但是我在这一行 scanf("%c", &op); 中收到一个错误,我在这里搜索 (Whosebug) 并且我还找到了答案,如果我在 scanf(" %c", &op) 中放置 space 那么我的程序将正常工作; 现在我的问题是,有人可以用通俗易懂的语言为初学者解释一下吗?请。非常感谢您的回答

在格式字符串中的转换说明符前加上 space 之类的

scanf( " %c", &op );
       ^^^^^  

在这种情况下,输入流中的白色 space 字符作为换行符 '\n' 对应于按下的 Enter 键将被跳过

请尝试使用 'getc' 和 'gets'。 'scanf' 被认为是完全不安全的,寻找更安全的替代品是明智的。这样您就可以更好地控制用户输入。

scanf 手册:

specifier c:

Matches a sequence of characters whose length is specified by the maximum field width (default 1); the next pointer must be a pointer to char, and there must be enough room for all the characters (no terminating null byte is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.

即格式scanf(" %c", &op).

输入 int num1 的第一个数字后,输入回车 '\n' 下一次字符扫描会捕获新行并打印出来。因此,根据手册,要先跳过白色 space,请使用格式明确的 space:

printf("Enter an operator: ");
scanf(" %c", &op);

或像下面这样使用:

printf("Enter an operator: ");
scanf("%c", &op);
scanf("%c", &op);

问题不在于 scanf,而在于 stdinstdinstdout 指的是控制台应用程序内存中的同一个文件。所以stdin中有'\n',你为第一个scanf输入的scanfscanf取出并存储在op中。试试把 scanf("%c", &op); 放在 scanf("%d", &num1); 上面或者把 fflush(stdin) 写在 scanf("%c", &op);

上面