当按下字符代替int时如何停止无限循环?

时间:2015-03-07 05:32:36

标签: c

这里,用户被要求按相应的键来执行特定的功能,但是假设我按下了任何字符值,例如“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:");
}
}

2 个答案:

答案 0 :(得分:0)

scanf()

之后添加此内容
char ch;

while( ( ch = getchar() ) != '\n' && ch != EOF );

这应该可以解决问题。

问题是由于scanf()不存储字符(因为您使用的是%d)导致问题,因此它们保留在输入缓冲区中。下一个scanf()尝试再次读取它,而不是存储它,忽略它并保留在缓冲区中。这个过程重复,导致无限循环。

我给出的代码读取缓冲区中的所有字符,从而重新推动无限循环。

干杯......希望这可以帮助你:)

答案 1 :(得分:-1)

这是一个非常棒的问题。你必须尝试在if()内使用break语句。

示例:

void main()
{

int n;

 printf("Enter the number 5\n");
while(1)
{
      scanf("%d",n);
      if(n==5)
      { break;
                         }
      else
      {
            printf(" enter the correct num again \n");

           }
   }
   printf(" you've entered the right number\n");

   }

你去这个程序会运行,直到你输入数字5

如果你想要任何整数 您可以使用头文件isdigit()

下的ctype函数