[英]fgets doesn't work (stdin looks full) in C
這是我的代碼,請看看。 我的菜單不斷循環播放,不要求任何輸入。 我不知道為什么fgets
不能按預期工作。
當我運行我的代碼時,即使我擺脫了循環,它也會繼續循環:
int main ()
{
char input[3];
char opt1;
int flag=1,n;
/*hrtime_t start, end;*/
dlist_t lst;
list_init (&lst);
list_input (&lst);
bubblesort (&lst);
list_display(&lst);
while(flag == 1)
{
printf("\nMain Menu\n");
printf("-----------\n");
printf("1. Bubble Sort\n");
printf("2. Selection Sort\n");
printf("3. Quick sort\n");
printf("4. Merge Sort\n");
printf("5. Exit\n");
printf("\nEnter your option[1-5]: ");
fgets(input, 3, stdin);
opt1 = input[0];
/* If condition to display the main menu if user inputs enter */
if(opt1 == '\n')
{
flag =1;
continue;
}
n = strlen(input)-1;
if(input[n] == '\n')
{
input[n] = '\0';
} else {
printf("\nInvalid input. ");
printf("Please note that the maximum length of the input is 1.");
readRestOfLine();
flag =1;
continue;
}
switch(opt1)
{
case '1':
/*start = gethrtime();
bubbleSort(list);
end = gethrtime();*/
printf("\nBubble Sorted List\n");
break;
case '2':
/* start = gethrtime();
selectionSort(list);
end = gethrtime(); */
printf("\nSelection Sorted List\n");
break;
case '3':
/*start = gethrtime();
quickSort(list, 0, list->list_len-1);
end = gethrtime(); */
printf("\nQuick Sorted List\n");
break;
case '4':
/*start = gethrtime();
list->head = mergeSort(list->head);
mergeSortReverse(list);
end = gethrtime(); */
printf("\nMerge Sorted List\n");
break;
case '5':
SNExit();
list_free (&lst);
printf("\n\n ********* THANK YOU **********");
return EXIT_SUCCESS;
default :
{
printf("\nPlease enter valid option\n");
break;
}
}
}
return EXIT_SUCCESS;
return 0;
}
/****************************************************************************
* Function readRestOfLine() is used for buffer clearing.
****************************************************************************/
void readRestOfLine()
{
int c;
/* Read until the end of the line or end-of-file. */
while ((c = fgetc(stdin)) != '\n' && c != EOF)
;
fflush(stdin);
/* Clear the error and end-of-file flags. */
clearerr(stdin);
}
我不知道...我運行了您的代碼,它對我來說很好用,所以我不知道您是怎么缺少輸入的。 您復制了完整代碼嗎?
由於您只使用第一個字符,為什么還要將其讀入緩沖區? 也許使用簡化的輸入可以避免出現錯誤,只需獲取char:
...
printf("4. Merge Sort\n");
printf("5. Exit\n");
printf("\nEnter your option[1-5]: ");
fflush(stdout);
opt1=getchar();
getchar(); // Extra "getchar" call to get rid of the newline
...
編輯:
讓我們嘗試簡化您的問題,以了解故障所在。 嘗試運行以下代碼:
int main()
{
char input = '0';
input = getchar();
getchar();
printf("%c\n", input);
return 0;
}
是否可以在您的系統上編譯/運行/工作? 如果是這樣,問題不在於您如何獲取字符串/字符,而與代碼有關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.