-1

Consider the following code:

while ((c = getchar()) != EOF)  // c is of char type 
      putchar(c);

getchar retrieves one char from the keyboard. But when I observed its execution, noticed that output of putchar does not take place until getchar encounters ENTER key. So isn't getchar actually retrieving the entire string until the ENTER key.

Actual Output:

Hello 
Hello 

Wanted Output:

H
H
E
E
L
L
O
O
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
Sachin P
  • 59
  • 5
  • I think you'll like this post (and its related posts): https://stackoverflow.com/questions/13104460/c-confusion-about-raw-vs-cooked-terminal-modes Your "H H E E L L O O" example is a Reasonable theory about how it Could work. Buffering, as described in the answers, prevents that interleaving. Turns out there are some options you can set that should give give you the "H H E E L L O O". The concept words "raw" vs "buffered" are not obvious until you know about them. Happy research. :-) – jgreve Jan 15 '16 at 16:10
  • also: https://stackoverflow.com/questions/1647927/unbuffered-i-o-in-ansi-c – jgreve Jan 15 '16 at 16:16
  • Thanks for the link. – Sachin P Jan 16 '16 at 05:10

3 Answers3

2

The stream is buffered, and the '\n' character flushes the buffer, so YES you need to press enter for the characters to strart "flushing".

Also, // c is of type char is wrong, since EOF cannot be represented then. The getchar() function returns int so c has to be of type int or c might overflow.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • Okay. But even if the stream is buffered, getchar needs to read one char from the buffer resulting in a true case of while loop and the same char being outputted and then the pointer in the buffer moves to the next char hence resulting in the wanted output! – Sachin P Jan 16 '16 at 05:20
0

When you enter the string Hello, then it goes to keyboard buffer. On pressing Enter/Reurn button, this stream of characters goes to standard input buffer and from there getchar reads it one by one.

Note that getchar returns int, so c should be of int type.

haccks
  • 104,019
  • 25
  • 176
  • 264
0

getchar() does not read keystrokes directly from the keyboard; it reads characters from an input stream, which is buffered such that input isn't sent to your program until you hit Enter.

If you need to read individual keystrokes as they are typed, then you will be better off using a platform-specific utility such as the getch function in the ncurses library to do so.

John Bode
  • 119,563
  • 19
  • 122
  • 198