读取用户命令继续不工作



我在写一个计费系统的程序。我在程序中使用了do-while循环。并根据用户输入执行程序。如果用户想要继续执行,程序将继续执行。但我在执行上有个问题。我只是在简单的do-while循环中尝试我的逻辑。同样的问题也会出现在简单的do-while循环中。

Problem is: If the input is yes, the program does not get the further input from user.

简单的do-while循环是:

#include <stdio.h>
main()
{
    int c;
    char ch;
    do
    {
            printf("enter the no less then 4:");
            scanf("%d",&c); 
        switch(c)
        {
            case 1:
                printf("In 1n");
                break;
            case 2:
                printf("In 2n");
                break;
            case 3:
                printf("In 3n");
                break;
        }
        printf("do u want to continue?:");
        ch=getchar();
    }while(ch=='y');
}

如果我把while(ch != 'n')代替while(ch=='y'),程序工作良好。我不明白这背后的问题。请帮我纠正这个错误。并解释一下这个问题。

第一次运行,输出3,用户输入"y"并按回车

getchar()读取'y'并循环

第二次

时,getchar()从上一个键

中读取换行符

换行符不是'y',所以程序不循环

几个问题:

  1. getchar返回int,而不是char,所以ch必须像c一样是int
  2. scanf需要一个指向%d的指针,所以应该是scanf("%d", &c);
  3. while应该测试EOF,如while ((ch = getchar()) != EOF)
  4. 注意,输入将包含换行符,您应该处理(例如忽略)。

这应该是相当健壮的:

#include <stdio.h>
int main(void)
{
  int c, ch;
  for (;;) {
    printf ("Enter a number (1, 2 or 3):");
    fflush (stdout);
    if (scanf ("%d", &c) == 1) {
      switch (c) {
      case 1:
        printf ("In 1n");
        break;
      case 2:
        printf ("In 2n");
        break;
      case 3:
        printf ("In 3n");
        break;
      }
      printf ("Do you want to continue? [y/n]:");
      fflush (stdout);
      while ((ch = getchar ())) {
        if (ch == 'y')
          break;
        else if (ch == 'n' || ch == EOF)
          return 0;
      }
    } else {
      printf ("That was not a number. Exiting.n");
      return 0;
    }
  }
}

While(ch=='y')或While()中的字符将按照您的编码....发送到case 3如果Y按下,它将被发送到case 3,否则它将不起作用

fgets代替getchar阅读答案

正如其他人解释的那样,第二个getchar调用给您换行符,它在第一个y之后键入。
使用fgets,您将获得用户键入的所有内容。然后你可以检查它是否为y(只检查第一个字符,或者使用strcmp)。

最新更新