这是我的代码,请看一下。我的菜单不断循环,不要求任何输入。我不知道为什么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);
}