#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"
请帮忙
最佳答案
- 当用户按下 Enter 键时,您的缓冲区中有一个换行符 (
\n
)。 - 您调用一次
getchar()
,从缓冲区中读取换行符,该换行符分配给ch
并且不等于'y'
或'Y'
,因此您的循环退出。
至于解决这个问题,留给你作为练习。除了单独的 getchar()
之外,您还可以考虑使用其他方法读取数据。参见 here对于某些输入函数(提示:fgets
)。您还可以尝试从缓冲区中提取此字符并将其丢弃,以便随后对 getchar()
的调用按预期工作。
如果这是针对学校的(看起来确实如此),您可能想要编写一个可以在整个类(class)中重复使用的函数。这样,您就可以对其进行调试,并熟悉它的工作原理。
祝你好运!
关于c - 为什么这段代码会提前退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3508242/