Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`getchar()` gives the same output as the input string

Tags:

c

eof

getchar

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?

like image 491
Shubham Avatar asked Sep 09 '10 13:09

Shubham


People also ask

What does the getchar () function do?

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.

Can I use Getchar for string?

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.

Is Getchar an output function?

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.

What is the problem with getchar ()?

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.


1 Answers

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.

like image 68
Erich Kitzmueller Avatar answered Oct 02 '22 16:10

Erich Kitzmueller