【发布时间】:2020-07-15 18:44:39
【问题描述】:
我正在用 C 语言创建一个计算器文件,其中包含 while 循环和 switch 语句。第一次通过while 循环,一切正常,但是当它通过第二次时,我的printf 在我有机会将数据输入到前面的scanf 之前被调用。
我尝试在printf 中的文本之前使用'\n',并且我也尝试在scanf 调用之前和之后使用fflush(stdout)。
当前输出:
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: A
Enter both numbers in required sequence: 50 50
// the output of the calculator does <>= 100 // Equal to 100.
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: Enter both numbers in required sequence:
我想要什么:
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: A
Enter both numbers in required sequence: 50 50
// the output of the calculator does <>= 100 // Equal to 100.
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: // then I can enter a new choice for the switch //
我试过的代码:
while(input != 'q'){
printf("Welcome to the Calculator\nOperation choices:\tAddition(A)\n\t\t\tSubtraction(S)\n\t\t\tMultiplication(M)\n\t\t\tDivision(D)\nEnter choice: ");
fflush(stdout);
scanf("%c", &input);
fflush(stdout);
printf("\nEnter both numbers in required sequence: ");
scanf("%f %f", &num1, &num2);
switch(input){
case 'A':
result = num1 + num2;
break;
case 'S':
result = num1 - num2;
break;
case 'M':
result = num1 * num2;
break;
case 'D':
result = num1 / num2;
break;
default:
printf("Please choose a valid operation.");
break;
}
if(result > 100){
printf("Greater than 100.\n");
}
else if(result < 100) {
printf("Less than 100.\n");
}
else{
printf("Equal to 100.\n");
}
}
printf("Quit the menu.\n");
return(0);
}
【问题讨论】:
-
不先检查
scanf的返回值就使用scanf的输出是不安全的。有关详细信息,请参阅此链接:A beginner's guide away from scanf() -
scanf("%c", &input);-->scanf(" %c", &input);
标签: c while-loop switch-statement printf scanf