尽管提供了适当的输入,循环仍未终止

时间:2013-01-30 16:38:16

标签: c while-loop scanf infinite-loop

尽管提供'n'作为输入,该程序仍会进入无限循环,以退出while循环。 可能是什么问题 ?

#include<stdio.h>
    main()
    {        
  int num,p=0,q=0,r=0;
    char check='y';

   while(check!='n')
     {
   printf("do you want to enter a number y or n");
    scanf("%c",&check);
    getchar();
    printf("enter a number");
     scanf("%d",&num);


    if(num>0)
      p++;
       else if(num<0)
      q++;
     else 
     r++;


    }
     printf("positive=%d\t negative=%d\t zero=%d\t",p,q,r);
        }

3 个答案:

答案 0 :(得分:1)

问题是在循环顶部重新评估while条件之前,循环不会退出。我建议你把你的循环改成这样的东西。

// we've purposely changed this to an infinite loop because
// we hop out on condition later
while(1)
{
    printf("do you want to enter a number y or n");
    scanf("%c",&check);
    getchar();

    // here's the code that will jump out of the loop early if the user
    // entered 'n'
    if('n' == check)
        break;

    // user didn't enter 'n'...they must want to enter a number
    printf("enter a number");
    scanf("%d",&num);

    if(num>0)
        p++;
    else if(num<0)
        q++;
    else 
        r++;
}

答案 1 :(得分:1)

while(check!='n')
{
    printf("do you want to enter a number y or n");
    scanf("%c",&check);
    getchar();
    printf("enter a number");
    scanf("%d",&num);

scanf("%d", &num);将换行符留在输入缓冲区中,因此在循环的下一次迭代中,存储在check中。之后,getchar()会消耗您输入的'n''y'。然后scanf("%d", &num);跳过缓冲区中剩下的换行符,扫描输入的数字,并将换行符保留在缓冲区中。您需要删除扫描数字之间的换行符,并查询是否要进行下一次迭代。

除此之外,最好在用户输入'n'后立即退出循环,所以

while(check!='n')
{
    printf("do you want to enter a number y or n");
    scanf("%c",&check);
    if (check == 'n') {
        break;
    }
    printf("enter a number");
    scanf("%d",&num);
    getchar();  // consume newline

会更好。如果用户输入不符合预期,那么仍然会对坏事开放,所以如果你想要一个健壮的程序,你需要检查scanf的返回值,以了解转换是否成功,并完全清空输入扫描前后的缓冲数。

答案 2 :(得分:0)

您没有检查字符输入。这应该是:

printf("do you want to enter a number y or n");
scanf("%c",&check);
/* This is what you need to add */
if (check == 'y') {
  getchar();
  printf("enter a number");
  scanf("%d",&num);
}