當scanf
成功轉換請求格式的輸入字符(本例中爲十進制整數"%d"
)時,返回1
表示「轉換成功」。掃描功能測試
嗯,我恐怕我不明白。
我想使用此功能來立即過濾輸入:如果輸入不是整數(正數或負數),則會請求另一個輸入。
#include<stdio.h>
#include<stdlib.h>
int main(){
int x;
printf("\nThis function reads an integer\n");
while(scanf("%d", &x) != 1){
printf("Please type an integer:\n");
scanf("%d", &x);
}
printf("\n%d is really an integer!\n", x);
return 0;
}
但在這種情況下,將2.15
輸入,scanf
只讀取數2
,然後成功地關閉循環。
也許你想使用浮點格式和類型?或者您可以閱讀整行(例如['fgets'](http://en.cppreference.com/w/c/io/fgets)),然後使用['strtol'](http:// en。 cppreference.com/w/c/string/byte/strtol)轉換爲整數?使用['strtol'](http://en.cppreference.com/w/c/string/byte/strtol),您可以檢查轉換結束的位置,以及是否轉換了整個字符串。 –
爲什麼你使用2次scanf? – tilz0R
@ tilz0R不是第一個(scanf(「%d」,x)== 1)邏輯條件? – Worice