3
    #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

Gabe
  • 84,912
  • 12
  • 139
  • 238
Vinod K
  • 1,885
  • 11
  • 35
  • 45
  • i am doing this program on linux...on virtual box.. – Vinod K Aug 18 '10 at 01:16
  • Please don't add homework tag before asking OP first. There is ample precedent for people asking homework-like questions for self-education and homework tags inevitably lead to either downvotes or obtuse/do-it-yourself answers when all the OP wants is a solution. Having said that, @Vinod, please indicate whether this _is_ homework. The style of answer changes depending on that. – paxdiablo Aug 18 '10 at 01:32
  • 1
    paxdiablo: I believe this falls squarely into the "plz send me teh codez" category. – Gabe Aug 18 '10 at 01:43
  • I disagree with @pax on the matter of identifying pedagogical questions. The fact that the OP sets it for him or herself is immaterial. I not a fan of [homework] for identifying such questions, but they are all the same. See [Etiquette on retagging questions as homework](http://meta.stackexchange.com/questions/41393/etiquette-on-retagging-questions-as-homework) for one of the several rounds of this on meta. And [this](http://meta.stackexchange.com/questions/49285/) [this](http://meta.stackexchange.com/questions/49874/) and a few others I can't find just now. – dmckee --- ex-moderator kitten Aug 18 '10 at 01:50
  • @Gabe: I disagree, the OP has a specific question. It's just the title that makes it seem like that. – mk12 Aug 18 '10 at 01:56
  • Gabe, this is most definitely _not_ a "send me the code" question. It may look at first glance like OP wants the code for the push/pop but they're actually asking a very specific "why does this one bit not work?" question. With regard to dmckee's comment, I have to invoke the recent http://blog.stackoverflow.com/2010/08/the-death-of-meta-tags/ : homework is very much a meta-tag that should be discouraged and, if OP wants guidance rather than a solution, they should specifically ask for that. Not saying I'm right and everyone else is wrong, just giving my reasoning. – paxdiablo Aug 18 '10 at 02:02
  • Changed the question title to match the question. Hopefully that will now be seen as less "send me the codez". – paxdiablo Aug 18 '10 at 02:06
  • A note to the OP: 1) It's `int main()` (ie, give `main` a return type) 2) Consistently indent your code: This will help readability, which in turn helps find syntax errors. – Thanatos Aug 18 '10 at 02:09
  • @pax: Understood. Did you see [Is homework an exception?](http://meta.stackexchange.com/questions/60422/is-homework-an-exception)? The question of [homework] seems to be hotly contended even after the doom of meta tags was announced. – dmckee --- ex-moderator kitten Aug 18 '10 at 02:14
  • 1
    I feel that having hijacked @Vinod's thread, we should state explicitly that homework (even real, got if from a teach have to turn it in homework] questions are OK on Stack Overflow. Please don't feel that you are being discouraged from looking here for help. But we generally want to see what you've tried and where you are stuck. This particular questions is absolutely fine. – dmckee --- ex-moderator kitten Aug 18 '10 at 02:21
  • @dmckee: yes, I did, but I don't actually agree with it :-) Hence my comment that "not saying I'm right ...". – paxdiablo Aug 18 '10 at 02:29
  • For the record, I agree with dmckee. If you always just give direct answers to pedagogical questions, SO becomes a place where 90% of the questions are "write/debug my program for me". Invariably these questions are poorly written (like "u plz hlp") and have poorly formatted code, reducing the signal-to-noise ratio to the point where experts won't want to hang out here and site becomes useless. – Gabe Aug 18 '10 at 04:25
  • @Gabe, you may well be right but the fact remains that this _wasn't_ a "write/debug my program for me" question. OP had a specific problem: why is the program exiting?. If they had wanted us to write `push` when all they gave us was `void push() {}`, I would have answered more obtusely or not at all. If the entire homework was to figure out why it was exiting, then I fear for the next generation of code cutters - they're going to be absolutely useless. I think it's more likely this was just a glitch found during a real assignment and fixing that in no way helps with the final solution. – paxdiablo Aug 18 '10 at 05:45
  • I suspect we're just going to have to agree to disagree, amicably, of course :-) – paxdiablo Aug 18 '10 at 05:45
  • paxdiablo: I have no problem with your answer (it's excellent, actually). What I don't understand is why you gave a pedagogical answer to what is obviously a pedagogical question, yet insist that the question not be tagged in such a way. – Gabe Aug 18 '10 at 13:44
  • Gabe, I'm not insisting, just stating my opinions - I'm not the only one here with the power to retag :-) But I don't see my answer as pedagogy. I provided a solution, plain and simple. I _did_ put a small bit at the end warning the OP just in case it was actually homework but that's just covering myself. – paxdiablo Aug 18 '10 at 13:51

3 Answers3

8
  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!

Nick Presta
  • 28,134
  • 6
  • 57
  • 76
5

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.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

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.

MikeJ
  • 14,430
  • 21
  • 71
  • 87