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

发布于 2024-09-14 23:21:21 字数 695 浏览 1 评论 0原文

    #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”并退出...不等待用户输入“”y/Y”

请帮忙

    #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()
 {
   }

The moment i finish with the push operation once...the program prints ""Do u want to continue y/n " and exits....doesnt wait for the user input "" y/Y"

Pls help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

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

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

如果这是为了学校(看起来是这样),您可能需要编写一个可以在整个课程中重复使用的函数。这样,您就可以调试它,并熟悉它的工作原理。

祝你好运!

  1. Your buffer has a newline (\n) in it from when the user pressed the Enter key.
  2. You call getchar() once, reading in that newline from the buffer, which is assigned to ch and does not equate to 'y' or 'Y', so your loop exits.

As for fixing this problem, that is left as an exercise to you. You could look into using other methods of reading in data besides a lone getchar(). See here for some input functions (hint: fgets). You could also try to extract this character from the buffer and discard it so subsequent calls to getchar() work as expected.

If this is for school, which it appears to be, you may want to write a function that you can reuse throughout your course. This way, you can debug it, and are familiar with how it works.

Good luck!

风吹过旳痕迹 2024-09-21 23:21:21

这是因为,当您输入 1 并按 RETURN 键时,两个 个字符将被放入缓冲区中(1 和一个 换行符)。

然后,newline 被第二个 getchar() 拾取,因为它既不是 Y 也不是 y,它退出了。

快速修复(但很笨拙):在 printf 之前放置另一个 getchar();

如果您想要更可靠的用户输入,请参阅此处,< a href="https://stackoverflow.com/questions/1247989/how-do-you-allow-spaces-to-be-entered-using-scanf/1248017#1248017">此处或在附近使用 我的武器库中的防弹代码:

#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;
}

-

// 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;
}

这是一个测试运行:

$ ./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]

您可能还想充实一下您的 pushpopdisplay 函数:-) 开个玩笑。我想这就是你的下一步。


顺便说一句,如果这是作业,我建议不要将上面的代码作为您自己的作业提交。你几乎肯定会被认为作弊,因为它很可能超出了你目前接受的教育水平,并且可以通过简单的网络搜索来找到它:进入

rc = getLine ("Enter string> ", buff, sizeof(buff));

你友好的邻居谷歌搜索框即可找到答案。

That's because, when you enter 1 followed by the RETURN key, two characters are put in your buffer (the 1 and a newline).

The newline is then picked up by the second getchar() and, since because that's neither Y nor y, it exits.

Quick fix (but kludgy): put another getchar(); before the printf.

If you want more robust user input, see here, here or use this near-bulletproof code from my arsenal:

#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;
}

 

// 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;
}

Here's a test run:

$ ./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]

You may also want to flesh out your push, pop and display functions a little :-) Just kidding. I'm assuming that's your next step.


By the way, if this is homework, I'd suggest not handing in that code above as your own work. You will almost certainly be picked up as cheating since it's most likely beyond the level of education you're currently receiving, and it's available with an easy web search: enter

rc = getLine ("Enter string> ", buff, sizeof(buff));

into your friendly neighbourhood Google search box to find out.

梦旅人picnic 2024-09-21 23:21:21

需要注意的小事。 getChar 返回 int 而不是 char。这可能会导致各种混乱和意外问题,因为类型可能大小不同。

Small thing to note. getChar returns int and not char. This can cause all kinds of mayhem and unexpected problems becuase the types are likely different sizes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文