Vin*_*d K 3 c stack programming-languages
#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()
{
}
Run Code Online (Sandbox Code Playgroud)
我完成推送操作的那一刻...程序打印""你想继续y/n"并退出....不等待用户输入""y/Y"
请帮忙
那是因为,当你输入1后跟RETURN
密钥时,你的缓冲区中会放入两个字符(1
a和a newline
).
在newline
随后由第二回升getchar()
,而且由于因为这是既不Y
也y
将退出.
快速修复(但kludgy):getchar();
在之前放另一个printf
.
如果您想要更强大的用户输入,请参阅此处,此处或使用我的武器库中的近防弹代码:
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
if (fgets (buff, sz, stdin) == NULL)
return NO_INPUT;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
}
Run Code Online (Sandbox Code Playgroud)
// Test program for getLine().
int main (void) {
int rc;
char buff[10];
rc = getLine ("Enter string> ", buff, sizeof(buff));
if (rc == NO_INPUT) {
// Extra NL since my system doesn't output that on EOF.
printf ("\nNo input\n");
return 1;
}
if (rc == TOO_LONG) {
printf ("Input too long [%s]\n", buff);
return 1;
}
printf ("OK [%s]\n", buff);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是一个测试运行:
$ ./tstprg
Enter string>[CTRL-D]
No input
$ ./tstprg
Enter string> a
OK [a]
$ ./tstprg
Enter string> hello
OK [hello]
$ ./tstprg
Enter string> hello there
Input too long [hello the]
$ ./tstprg
Enter string> I am pax
OK [I am pax]
Run Code Online (Sandbox Code Playgroud)
你可能也想充实你的push
,pop
并且display
运作一点:-)开个玩笑.我假设这是你的下一步.
顺便说一下,如果这是家庭作业,我建议不要把上面的代码作为你自己的工作.你几乎肯定会被当作作弊,因为它最有可能超出你目前接受的教育水平,而且它可以通过简单的网络搜索获得:输入
rc = getLine ("Enter string> ", buff, sizeof(buff));
Run Code Online (Sandbox Code Playgroud)
进入你友好的邻居谷歌搜索框找出来.