c - 当使用 scanf 获取整数和 char 值时,程序会跳过 scanf

标签 c char scanf

#include <stdio.h>


int multiple(int num1,int num2){
    return (num1*num2);
}

int add(int num1, int num2){
    return (num1+num2);
}
/*&x points to its value space *x points to its memory space*/
int main(){

    int num1,num2,ans;
    char func;

    printf("First number => ");
    scanf("%d",&num1);
    printf("Second number => ");
    scanf("%d",&num2);

    printf("Please Enter + for addition, or * for multiplication => ");
    scanf("%c",&func);

    if (func == '*'){
        ans = multiple(num1,num2);
    }else if(func == '+') {
        ans = add(num1,num2);
    }else {
        printf("Sorry, invalid operation");
    }

    printf("Ans : %d",ans);
    return 0;
}

当我运行程序时,它会提示我输入第一个和第二个数字,但它不会提示我输入字符 scanf("%c",&func);没有被执行。

我的输出-------------------------------------------------------- --------------------:

$ ./p8t3 First number => 23 Second number => 32 Please Enter + for addition, or * for multiplication => Sorry, invalid operationAns : 2665616

最佳答案

在扫描 + 或 * 运算符时,进行如下更改:

printf("Please Enter + for addition, or * for multiplication => ");
scanf(" %c",&func);         //use a space before '%c'

关于c - 当使用 scanf 获取整数和 char 值时,程序会跳过 scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17631851/

相关文章:

c - 使用 strtok 在 C 中解析字符串

C计算字符串中某个字符出现的次数

c - 在 C 中声明不带引号的字符变量

c - 从多维数组中提取时序并写入c中的文件

c - 为什么指针不递增?

python - 将C公式转换为Python

c - 通过 C 中的标准输入读取大型列表

c - 如何从 char *functionName(int arrayname[SIZE]); 返回字符数组

c - Scanf 不情愿地删除一个字符数组

C/C++ printf() 在 scanf() 问题之前