我在我的代碼下面遇到問題。當我輸入任何整數,即(0-9)
,那麼它是確定的。但是,當我輸入其他字符如A
,B
或任何其他字母scanf()
失敗。然後它不會等待任何進一步的輸入。爲什麼scanf在一次失敗後不等待用戶輸入?
我附上了一個代碼片段。我非常需要僅使用C標準庫的錯誤處理。
#include <stdio.h>
int main()
{
int choice;
while(1)
{
printf("Enter your choice: ");
if(0 == scanf("%d", &choice))
{
printf("Some error occured\n");
//break;/*I did not want to break this loop as I use this to show menu*/
}
switch(choice)
{
case 0:printf("Case 0\n");break;
case 1:printf("Case 1\n");break;
case 2:printf("Case 2\n");break;
case 3:printf("Case 3\n");break;
case 4:printf("Case 4\n");break;
case 5:printf("Case 5\n");break;
case 6:printf("Case 6\n");break;
case 7:printf("Case 7\n");break;
case 8:printf("Case 8\n");break;
case 9:printf("Case 9\n");break;
default:printf("Default case\n");break;
}
}
}
更清楚的問題是:爲什麼在失敗後等待?
這工作正常,但是C庫提供了一些設施來清除輸入緩衝區。就像它們爲輸出緩衝區提供像fflush()一樣的工具。 – rajesh6115 2012-08-04 02:44:13
不,沒有標準的工具來清除輸入緩衝區(儘管有些實現可能提供它)。只要閱讀輸入,例如使用fgets()。這只是一個像fflush()一樣的函數調用。 – nos 2012-08-04 02:48:02
謝謝你的回答... – rajesh6115 2012-08-04 02:53:22