2013-10-07 26 views
3

我抓住用戶的一些標準輸入,如果用戶按下CTRL + D ,我想顯示一個錯誤並終止程序。我想也許我的問題可能與陷入一段時間循環有關;fgets和處理CTRL + D輸入

int readInput(){ 
    char buff[10]; 
    int count = 0; 
    int counter; 
    printf("Enter random number: "); 
    fgets(buff, 10, stdin); 
    if ((int) strtol(buff, NULL, 10) == 0){ 
     printf("Error reading number. \n"); 
     return 0; //This will get hit if the user presses CTRL+D at this input. 
    } 
    counter = atol(buff); 
    while (count < counter){ 
     printf("Enter a label: "); 
     fgets(buff, 10, stdin); 
     if ((int) strtol(buff, NULL, 10) == 0){ 
     printf("Error reading label"); 
     return 0; //This will not get hit if the user presses CTRL+D at this input, but why? 
     //I've also tried assigning a variable to 0, breaking out of the loop using break; and returning the variable at the end of the function but that also does not work. 

     //the rest of the while loop continues even if user hit CTRL+D 
     printf("Enter Value: "); 
     fgets(buff, 10, stdin); 
     //..rest of while loop just gets other inputs like above 
     count++; 
    } 

//termination happens in main, if readInput returns a 0 we call RETURN EXIT_FAILURE; 

我不明白,爲什麼在第一次輸入,如果用戶按下CTRL + d,程序作出相應的響應,但第二次它完全忽略它。

+0

計數器在while循環遞增的方式是好奇。另外,計數是否增加? – ryyker

+0

操作系統Linux? –

+0

這是在Ubuntu的機器上,是的。 –

回答

7

在Linux上,Ctrl + D生成EOF,所以你需要每次檢查返回值fgets()。當遇到EOFfgets()返回一個空指針

if (fgets(buff, 10, stdin) == NULL) 
    print_error(); 
+0

理解,關於爲什麼CTRL + D的第一次檢查工作正常的任何想法? –

+0

由於D自動初始化緩衝區爲'\ 0'(至少在調試模式下),並且在第二次測試中,您仍舊擁有舊版本的buff值。「# –

+1

@YuHao buff中的任何非數字字符都會讓strtol返回0,所以這是一個10中256的機會不工作 –