[英]How to stop infinite loop when character is pressed in place of int?
在這里,要求用戶按相應的鍵來執行特定的功能,但是假設我按了任何字符值(例如“ 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 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
如果需要任何整數,可以使用頭文件ctype
下的isdigit()
函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.