【问题标题】:Program skips scanf when using scanf for integer along with char values [duplicate]将 scanf 用于整数和 char 值时,程序会跳过 scanf [重复]
【发布时间】:2013-07-13 16:02:29
【问题描述】:
#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",&amp;func); 没有被执行。

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

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

【问题讨论】:

标签: c char scanf


【解决方案1】:

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

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

【讨论】:

  • 这行得通!谢谢,虽然我不确定这背后的原因是什么.. 编辑:找到原因stackoverflow.com/q/14484431/2016977
  • @DeepakTivari 在将第二个数字作为输入后,换行符仍然存在于缓冲区中。如果您使用 scanf("%c", &func),它将读取换行符作为输入,从而导致错误的行为。如果使用 scanf(" %c", &func),scanf 会忽略换行符并等待用户输入。
  • 这对我帮助很大。非常感谢!
【解决方案2】:
printf("Please Enter + for addition, or * for multiplication => ");
scanf(" %c",&func);

原因是当你输入一个数字并按 ENTER 时,scanf 将处理该数字,但新行仍在输入缓冲区中。

【讨论】:

    猜你喜欢
    • 2013-01-07
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多