2015-11-22 18 views
0

所以,這個程序接受三個值,一個int,一個float和一個char,同時在一個循環中。 當它要求用戶輸入整數並且他們寫入..讓我們說,「衆議院」程序陷入無限循環。在循環中獲取與預期值不同的值。爲什麼?

#include <stdio.h> 

int main(void){ 

    int i; 
    float f; 
    char c; 

    while(i!=99){ 

     printf("Enter an int, a float and a char separated by commas: "); 
     int count = scanf("%d,%f,%c",&i,&f,&c); 
     printf("Int is: %d, Float is: %1.f, Char is: %c",i,f,c); 

     if (count != 2){ 
      fflush(stdin); 
      printf("\nerror\n"); 
     } 

    } 

    return 0; 
} 
+3

'i'不循環條件使用它''同時初始化之前。 – haccks

+0

不僅'i'可以用於初始化,而且可以用於所有變量('count'除外)。這是因爲第一次調用'scanf'可能會失敗。 – Olaf

回答

1

在這 -

if (count != 2){ 
     fflush(stdin);     // undefined behaviour 
     printf("\nerror\n"); 
    } 

而且count應該對3測試不2scanf將返回3如果全成)。取而代之的fflush(stdin),以此來清除輸入

於流
int c; 
if (count != 3){ 
    while((c=getchar())!='\n' && c!= EOF); 
    printf("\nerror\n"); 
} 

還你i初始化。所以,無論是初始化而不是使用while循環使用do-while,或 -

未解釋爲數據讀取,所以在接下來的迭代
do{ 
    //your code 
    }while(i!=99); 
+0

@hydrz我不確定你在說哪個循環? – ameyCU

+0

哦,那有效!是的,我忘記了一些事情,因爲我只是爲了在這裏詢問它而編寫代碼。順便說一句,你能解釋一下嗎? 「while((c = getchar())!='\ n'&& c!= EOF);」我的意思是。 – hydrz

+0

@hydrz內部'while'循環將從'stdin'中讀取並存儲在'c'中,直到遇到新行或'EOF'。這樣'stdin'將被清除,並且在下一次迭代中'scanf'不會失敗。 – ameyCU

1
  • scanf()假字,scanf()再次嘗試讀取字符和失敗再次,它會造成無限循環。
  • fflush(stdin);是未定義的行爲,不使用它。
  • 未初始化的i用於i!=99,這也是未定義的行爲。

試試這個:(!I = 99)

#include <stdio.h> 

int main(void){ 

    int i=0; 
    float f=0.0f; 
    char c=' '; 

    while(i!=99){ 

     printf("Enter an int, a float and a char separated by commas: "); 
     int count = scanf("%d,%f,%c",&i,&f,&c); 
     printf("Int is: %d, Float is: %1.f, Char is: %c",i,f,c); 

     if (count != 3){ /* adjusted to match the scanf */ 
      int dummy; 
      while((dummy=getchar())!='\n' && dummy!=EOF); /* skip one line */ 
      printf("\nerror\n"); 
      if (dummy == EOF) break; /* there won't be any more input... */ 
     } 

    } 

    return 0; 
}