1

Second getchar function is not waiting for user input. Could not figure out what is missing in the following code

char ch = 'n';
bool status = false;

printf("%s", "Some text1\n");
ch = getchar();

if ((ch == 'Y') || (ch == 'y'))
{
    status = true;
}

if(status)
{
    printf("%s", "Some text2\n");
    ch = getchar();

    if ((ch == 'Y') || (ch == 'y'))
    {
        status = eNoError;
    }
}
Arun
  • 2,247
  • 3
  • 28
  • 51

2 Answers2

5

That's because of a newline character.

When you enter first 'Y', you actually enter a string like "Y\n".

First getchar() reads 'Y', and '\n' sits in a buffer. So the second getchar() gets that '\n' character.

WGH
  • 3,222
  • 2
  • 29
  • 42
  • ok. do I need another getchar() to get input? or is there any better way to handle this – Arun Feb 11 '16 at 13:45
  • I believe the simplest way to overcome this would be to use `scanf(" %c", &c)`, as per http://stackoverflow.com/a/18627241/371970 – WGH Feb 11 '16 at 13:49
  • This check need to be there after each getchar.do { c = getchar(); }while(c != '\n' && c != EOF); – Arun Feb 11 '16 at 14:18
2

I'm sorry to necro this post but I'm posting this in case anyone else runs into this problem and wants a better answer. The easiest way around this is to flush the input somewhere between the first getchar and the second:

ch = getchar();
fflush(stdin); // can be anywhere in between the getchar() calls
ch = getchar();

Hopefully this helps someone out moving forward

Jack
  • 21
  • 1