I am confused by a program mentioned in K&R that uses getchar()
. It gives the same output as the input string:
#include <stdio.h> main(){ int c; c = getchar(); while(c != EOF){ putchar(c); c = getchar(); } }
Why does it print the whole string? I would expect it to read a character and ask again for the input.
And, are all strings we enter terminated by an EOF?
getchar is a function in C programming language that reads a single character from the standard input stream stdin, regardless of what it is, and returns it to the program. It is specified in ANSI-C and is the most basic input function in C. It is included in the stdio.
It reads the specified amount to the string, but the getchar is still filling up the buffer until the user manually enters a newline by pressing enter.
putchar(), getchar() function in C: putchar() function is a file handling function in C programming language which is used to write a character on standard output/screen. getchar() function is used to get/read a character from keyboard input.
Originally Answered: What is the problem with getchar()? Getchar() is one of the function which is used to take input from the user. But at a time it can take only one character.. if the user give more than one character also,it reads only one character.
In the simple setup you are likely using, getchar
works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF
; in fact, EOF
is not really a character, but a magic value that indicates the end of the file. But EOF
is not part of the string read. It's what getchar
returns when there is nothing left to read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With