gpt4 book ai didi

c - fgets 和处理 CTRL+D 输入

转载 作者:IT王子 更新时间:2023-10-29 01:01:15 24 4
gpt4 key购买 nike

我正在从用户那里获取一些标准输入,如果用户按下 CTRL+D,我想显示错误并终止程序。我想我的问题可能与陷入 while 循环有关;

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,程序会做出相应的响应,但第二次它会完全忽略它。

最佳答案

在Linux上,Ctrl + D会产生EOF,所以每次都需要检查fgets()的返回值。当遇到EOF时,fgets()返回一个空指针

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

关于c - fgets 和处理 CTRL+D 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19228645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com