-
infintite loop
I have a pice of code
Code:
do
{
clrscr();
printf("\n\n\t\t <<< MAIN MENU >>>");
printf("\n\n\t 1. Insert ");
printf("\n\n\t 2. Delete ");
printf("\n\n\t 0. Exit ");
printf("\n\n\t\t Enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1 : printf("\n Enter data to be inserted : ");
scanf("%d",&data);
enqueue(&qarr,data);
printf("\n\nThe queue is :-\n\n");
display(qarr);
break;
case 2 : printf("\n\nBefore Deletion queue is :-\n\n");
display(qarr);
dequeue(&qarr);
printf("\n\nThe new queue is :-\n\n");
display(qarr);
break;
case 0 :exit(0);
default: printf("\n Invalid Choice, try Again !!!");
}
printf("\n\n\n\n\t\t Press any key to continue...");
getch();
}
while(1);
if during runtime i input a character into choice instead of an integer the progam goes into infinite loop.
I know how to rectify the problem. Bt i don't know why the reason due to which the program is going into an infinite loop. Please help
-
Code:
char c;
while ((c = getchar()) != EOF && c != '\n');
This should consume any characters that were not assigned to variables by scanf().
NB!
You can get some funky behavior if there are no characters to consume.
-
Thanks, but can you please tll me why is the program going into an infinite loop in the first place?
-
Ah. Sure. Because you never do anything to break out of the do-while loop, except in case 0 where you exit the program. There's still input in the buffer that scanf() can't assign to ch so you get the default case again and do-while loop runs again. Ad nauseam.
-
Code:
int c;
while ((c = getchar()) != EOF && c != '\n');
Question 12.1
-
Thanks. I keep missing that.