c - 为什么这段代码会提前退出?

标签 c programming-languages stack

    #include <stdio.h>
    #define MAX 5
    int stk[MAX];
    int top=-1;

    main() 
     {
      char ch;
      void push();
      void pop();
     void display();

     do
     {
      printf("1. Push\n");
      printf("2. Pop\n");
      printf("3. Display\n");
      ch=getchar();

         if(ch=='1')
            push();
         if(ch=='2')
            pop();
         if(ch=='3')
            display();

    printf("Do u want to continue y/n"); 
    ch=getchar();
       }while(ch=='y'||ch=='Y');

    }

void push()
 {
   }

void pop()
 {
   }

void display()
 {
   }

我完成一次推送操作的那一刻...程序打印“"Do u want to continue y/n "and exits...doesnt wait for the user input ""y/Y"

请帮忙

最佳答案

  1. 当用户按下 Enter 键时,您的缓冲区中有一个换行符 (\n)。
  2. 您调用一次 getchar(),从缓冲区中读取换行符,该换行符分配给 ch 并且不等于 'y''Y',因此您的循环退出。

至于解决这个问题,留给你作为练习。除了单独的 getchar() 之外,您还可以考虑使用其他方法读取数据。参见 here对于某些输入函数(提示:fgets)。您还可以尝试从缓冲区中提取此字符并将其丢弃,以便随后对 getchar() 的调用按预期工作。

如果这是针对学校的(看起来确实如此),您可能想要编写一个可以在整个类(class)中重复使用的函数。这样,您就可以对其进行调试,并熟悉它的工作原理。

祝你好运!

关于c - 为什么这段代码会提前退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3508242/

相关文章:

c - 是否可以在 NDIS 层捕获 localhost 数据包(127.0.0.1 作为目标)?

programming-languages - 像芥末一样的网络编程语言

user-interface - 想要一种除了 Java 之外的具有 GUI 优势的新语言

python - 不要在异常堆栈中显示 Python raise-line

c - 使用数组实现动态大小的堆栈,元素打印错误

c - 我如何跟踪 gcc 中的变量变化

c - xcode编译控制台应用程序-c编程

c++ - 继承 std::stack 会导致 clang 出错,但适用于 gcc

c++ - 堆栈限制和线程之间的关系

c - 声音设备停止工作 PJSUA - 下溢错误