fgets和处理CTRL + D输入

问题描述:

我抓住用户的一些标准输入,如果用户按下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的机器上,是的。 –

在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的机会不工作 –