[英]Scanf doesn't work as expected in VS Code
我练习了一个简单的例子,在 C 中输入运算符:代码如下:
#include <stdio.h>
int main() {
int a,b;
char opera;
printf("input 2 integer number ");
scanf("%d %d",&a,&b);
printf("\n input the operator: ");
scanf("%c", &opera);
switch (opera)
{
case '+':
printf("result is %d \n", a+b);
break;
default:
break;
}
}
问题:终端将通过输入运算符
input 2 integer number
4 5
input the operator:
PS D:\Quang\3. Study\C\Bai 2\.vscode>
但如果我先输入操作,它会起作用:
#include <stdio.h>
int main() {
int a,b;
char opera;
printf("\n input the operator: ");
scanf("%c", &opera);
printf("input 2 integer number");
scanf("%d %d",&a,&b);
switch (opera)
{
case '+':
printf("result is %d \n",a+b);
break;
default:
break;
}
}
结果:
input the operator: +
input 2 integer number 4 5
result is 9
有人对 VS Code 有同样的问题吗?
那么在扫描两个整数之后, stdin缓冲区不是空的,一个'\n'
新行字符留在那里,所以在读取一个字符作为运算符之后,你实际上读取了那个新行字符,所以你可以通过制作来解决这个问题自定义刷新 function,它只读取留在标准输入中的字符,如下所示:
#include <stdio.h>
// make stdin buffer empty
void flush() {
int c;
while(1) {
c = fgetc(stdin);
if(c == EOF || c == '\n') break;
}
}
int main() {
int a, b;
char opera;
printf("input 2 integer number ");
scanf("%d %d",&a,&b);
flush();
printf("input the operator: ");
scanf("%c", &opera);
// I have added other operators
switch (opera) {
case '+': printf("result is %d", a + b); break;
case '-': printf("result is %d", a - b); break;
case '/': printf("result is %d", a / b); break;
case '*': printf("result is %d", a * b); break;
case '%': printf("result is %d", a % b); break;
default: printf("unknown operation");
}
}
或者只是在读取实际运算符之前使用 scanf 读取新行字符,如下所示:
#include <stdio.h>
int main() {
int a, b;
char opera;
printf("input 2 integer number ");
scanf("%d %d",&a,&b);
printf("input the operator: ");
// read the new line char before reading the operator
scanf(" %c", &opera);
// I have added other operators
switch(opera) {
case '+': printf("result is %d", a + b); break;
case '-': printf("result is %d", a - b); break;
case '/': printf("result is %d", a / b); break;
case '*': printf("result is %d", a * b); break;
case '%': printf("result is %d", a % b); break;
default: printf("unknown operation");
}
}
结果:
input 2 integer number 4 5
input the operator: *
result is 20
那是因为您首先输入了2个数字...
input 2 integer number 4 5
最后,您按回车键。 所以这个 '\n' 字符存储在输入缓冲区中......当你的下一条语句执行时:
scanf("%c", &opera);
此输入由缓冲区中已存在的 '\n' 完成。 这会导致跳过输入。
解决方案:-
使用以下语句。
scanf(" %c",&opera); // Any extra spaces or newline will be discarded...
你想读这个:-
有两种方法可以解决这个问题:
scanf(..., &opera)
语句之前使用fflush(stdin)
。 如果您不想执行上述步骤,只需在scanf(..., &opera)
的%c
字符之前留一个空格,例如:
scanf(" %c", &opera);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.