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.