Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does `getchar()` store the user input?

I've started reading "The C Programming Language" (K&R) and I have a doubt about the getchar() function.

For example this code:

#include <stdio.h>

main()
{
  int c;

  c = getchar();
  putchar(c);
  printf("\n");   
}

Typing toomanychars + CTRL+D (EOF) prints just t. I think that's expected since it's the first character introduced.

But then this other piece of code:

#include <stdio.h>

main()
{
  int c;

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

Typing toomanychars + CTRL+D (EOF) prints toomanychars.

My question is, why does this happens if I only have a single char variable? where are the rest of the characters stored?

EDIT:

Thanks to everyone for the answers, I start to get it now... only one catch:

The first program exits when given CTRL+D while the second prints the whole string and then waits for more user input. Why does it waits for another string and does not exit like the first?

like image 460
Pablo Fernandez Avatar asked Jun 16 '09 22:06

Pablo Fernandez


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.

What does the function getchar () return at the end-of-file?

The getc() and getchar() functions return the character read. A return value of EOF indicates an error or end-of-file condition. Use ferror() or feof() to determine whether an error or an end-of-file condition occurred.

What value does getchar () return when there is no more data available from standard input?

The getchar routine will return the special value EOF (usually -1; short for end of file) if there are no more characters to read, which can happen when you hit the end of a file or when the user types the end-of-file key control-D to the terminal.

Why does Getchar return an int?

getchar() returns int , which will be at least 16 bits (usually 32 bits on modern machines). This means that it can store the range of char , as well as more values. The reason why the return type is int is because the special value EOF is returned when the end of the input stream is reached.


1 Answers

getchar gets a single character from the standard input, which in this case is the keyboard buffer.

In the second example, the getchar function is in a while loop which continues until it encounters a EOF, so it will keep looping and retrieve a character (and print the character to screen) until the input becomes empty.

Successive calls to getchar will get successive characters which are coming from the input.

Oh, and don't feel bad for asking this question -- I was puzzled when I first encountered this issue as well.

like image 96
coobird Avatar answered Oct 12 '22 21:10

coobird