这里,用户被要求按下相应的键来执行特定的功能,但假设我按下了任何字符值,如"g",它就会进入无限循环。
如何解决这个问题?
int item,choice;
clrscr();
while(1)
{
printf("QUEUE SIMULAtOR");
printf("n1:Insert");
printf("n2:Delete");
printf("n3:Display");
printf("nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:qinsert();
break;
case 2:item=qdelete();
if(item!=-1)
printf("Deleted item is %d",item);
break;
case 3:printf("nElements in the queue are:");
qdisplay();
break;
case 4:exit(0);
default:printf("nWrong choice try again:");
}
}
将其添加到scanf()
之后
char ch;
while( ( ch = getchar() ) != 'n' && ch != EOF );
这应该奏效。
问题的原因是scanf()
不存储字符(因为您使用的是%d),因此它们保留在输入缓冲区中。下一个scanf()
尝试读取此内容,并再次忽略它,而不是存储它,它将保留在缓冲区中。这个过程重复,从而导致无限循环。
我给出的代码读取缓冲区中的所有字符,从而重新移动无限循环。
干杯。。。希望这能帮助您:)
这是一个非常棒的问题。您必须尝试在if()
中使用break语句。
示例:
void main()
{
int n;
printf("Enter the number 5n");
while(1)
{
scanf("%d",n);
if(n==5)
{ break;
}
else
{
printf(" enter the correct num again n");
}
}
printf(" you've entered the right numbern");
}
在那里,这个程序将运行,直到你输入数字5
如果您想要任何整数您可以使用头文件ctype
下的isdigit()
函数