Scanf无法正常工作

时间:2017-04-26 14:35:41

标签: c char printf character scanf

在我的代码中,第二个scanf不起作用,无法读取该字符。 我该如何解决?

#include <stdio.h>
int main() {
int a, result;
// ***************** Menu *******************
printf("Hello !!! \n The Operations That This Calculator Can Do :");
printf("\n1. Simple Operations");
printf("\n2. Calculate The Biggest Number");
printf("\n3. Taylor expansion");
printf("\n4. Sum Digits Of a Number");
printf("\n5. Found The Prime Numbers Before The Number That You Entered");
printf("\nEnter The Number Of Operation That You Want : ");
scanf_s("%d", &a);
if (a == 1){
    char ch;
    int num1, num2;
    printf("\n Please Enter Your Operation Like That (- 5 3 ) : ");
    scanf_s("%c", &ch);
    if (ch == '-'){ scanf_s("%d", &num1); scanf_s("%d", &num2); result = num1 - num2; printf("\n > %d", result); }
    if (ch == '+'){ scanf_s("%d", &num1); scanf_s("%d", &num2); result = num1 + num2; printf("\n > %d", result); }  }  return 0; }

1 个答案:

答案 0 :(得分:0)

试试这个:我将scanf_s()更改为scanf并为%c提供空间,因为%c转换说明符不会自动跳过任何前导空格,所以如果输入流中有一个错误的换行符(例如,从上一个条目开始,scanf调用将立即使用它。

#include <stdio.h>
int main() {
int a, result;
// ***************** Menu *******************
printf("Hello !!! \n The Operations That This Calculator Can Do :");
printf("\n1. Simple Operations");
printf("\n2. Calculate The Biggest Number");
printf("\n3. Taylor expansion");
printf("\n4. Sum Digits Of a Number");
printf("\n5. Found The Prime Numbers Before The Number That You Entered");
printf("\nEnter The Number Of Operation That You Want : ");
scanf("%d", &a);
if (a == 1){
char ch;
int num1, num2;
printf("\n Please Enter Your Operation Like That (- 5 3 ) : ");
scanf(" %c", &ch);
if (ch == '-'){ scanf(" %d", &num1); scanf(" %d", &num2); result = num1 - 
num2; printf("\n > %d", result); }
if (ch == '+'){ scanf(" %d", &num1); scanf(" %d", &num2); result = num1 + 
num2; printf("\n > %d", result); }  }
system("pause"); }