Search code examples
cgetchar

getchar() continues to accept input after including Ctrl+Z in same line


Simple c program to accept and print the character.

int c;
while((c=getchar())!=EOF)
{
  putchar(c);
}

I am not getting why it accept input when I press Ctrl+Z at the end of line ex Hello(press Ctrl+Z) hello (some symbol) but it work properly after leaving a line then pressing Ctrl+Z. And I am using Window 7

Ouput


Solution

  • When you call getchar() it in turn ends up making a read() system call. The read() will block until it has some characters available. The terminal driver only makes characters available when you press the return key or the key signifying end of input. At least that is what it looks like. In reality, it's more involved.

    On the assumption that by ctrl-Z you mean whatever keystroke combination means "end of input", the reason is the way that the read() system call works. The ctrl-D (it's ctrl-D on most Unixes) character doesn't mean "end of input", it means "send the current pending input to the application".

    When you've typed something in before pressing ctrl-D, that input gets sent to the application which is probably blocked on the read() system call. read() fills a buffer with the input and returns the number of bytes it put in the buffer.

    When you press ctrl-D without any input pending (i.e. the last thing you didwas hit return or ctrl-D, the same thing happens but there are no characters, so read() returns 0. read() returning 0 is the convention for end of input. When getchar() sees this, it returns EOF to the calling program.

    This answer in Stack Exchange puts it a bit more clearly

    https://unix.stackexchange.com/a/177662/6555