[英]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.