本文介绍了fgets和CTRL + D输入处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从用户那里获取一些标准输入,如果用户按下,我想显示一个错误并终止程序.我认为我的问题可能与卡在while循环中有关;
I am grabbing some standard input from the user and if the user presses , I want to display an error and terminate the program. I think perhaps my issue may be related to being stuck in a while loop;
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;
我不明白为什么在用户按下的第一次输入时,程序会做出相应的响应,而第二次却完全忽略了它.
I don't understand why at the first input if the user presses , the program responds accordingly but the second time it completely ignores it.
推荐答案
在Linux上,生成EOF
,因此您需要每次检查fgets()
的返回值.遇到EOF
时,fgets()
返回空指针
On Linux, generates EOF
, so you need to check the return value of fgets()
every time. When EOF
is encountered, fgets()
returns a null pointer
if (fgets(buff, 10, stdin) == NULL)
print_error();
这篇关于fgets和CTRL + D输入处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!