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

我试图用用户输入构建一个基本的计算器。但是我在这里(Stackoverflow)搜索的这一行出现错误,scanf("%c", &op);我还找到了答案,如果我在其中放置一个空格,scanf(" %c", &op)那么我的程序将正常工作;现在我的问题是,有人可以用外行的方式为初学者解释一下吗?请。您的回答将不胜感激

4

4 回答 4

0

在格式字符串中的转换说明符前面加上一个空格,例如

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

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

于 2021-11-07T12:34:40.337 回答
0

scanf手动的:

说明符 c:

匹配长度由最大字段宽度指定的字符序列(默认为 1);next 指针必须是指向 char 的指针,并且必须有足够的空间容纳所有字符(不添加终止空字节)。前导空白的通常跳过被抑制。要先跳过空格,请在格式中使用显式空格。

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

int num1在为您键入第一个数字后,输入'\n'下一个字符扫描捕获新行并打印它。因此,根据手册,要先跳过空格,请使用以下格式的显式空格:

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

或像下面这样使用:

printf("Enter an operator: ");
scanf("%c", &op);
scanf("%c", &op);
于 2021-11-07T12:54:07.143 回答
0

问题不在于scanfbut stdinstdinstdout为控制台应用程序引用内存中的相同文件。因此,'\n'stdin您首先输入的内容中,有一些内容scanf被. 尝试放在上面或写在上面scanfopscanf("%c", &op);scanf("%d", &num1);fflush(stdin)scanf("%c", &op);

于 2021-11-07T12:54:17.980 回答
-3

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

于 2021-11-07T12:36:17.400 回答