can someone explain me getchar ()! = EOF?


I do not understand very well how getchar and putchar works, for example:

    double nc;
    for (nc=0; getchar() != EOF; ++nc)
    printf("%.0f\n", nc);
asked by belen21 03.10.2016 в 07:09

1 answer

  • getchar () is a function that allows you to read a character from standard input.
  • putchar () is a function that allows you to write a character in the standard output.

If you review the documentation on getchar (get used to doing it if you want your programs to work like you pretend), you will see that the return type is a int instead of a char . The reason is that this function must be able to return certain special characters such as the end of file ( EOF for friends). Discarding the special sequences (I now only remember EOF ), the rest of the values can be quietly converted to char for your own purposes:

int valor = getchar();
if( valor != EOF )
  char c = (char)valor;

As for putchar , its mechanics are exactly the same only that instead of reading , write in the standard output.

As a bonus, notice that at the beginning I talked about standard input and standard output instead of keyboard and console By default, the input buffer will be filled from the keyboard and the output buffer will be redirected to the console, but bear in mind that it does not necessarily have to be this way. When you execute an application you can redirect the input and the output to, for example, a file, so that the application will not read the keyboard but a file and will not print anything on the screen but will dump a series of messages in the corresponding file .

It is for reasons like this that sometimes the documentation of the functions can be confusing. People get used to talking about keyboard and screen when it really does not have to be like that.

An example in Windows could be:

miApp < ficheroDeEntrada > ficheroDeSalida

And going back to your question. The code you have set does the following:

  • Read from the standard input item by item until it reaches the end.
  • For each item read, increase the value of nc . Note that nc is independent of getchar .
  • Print the value of nc .

A slightly more readable version could be:

  int nc = 0; // Para enteros mejor int
  while( getchar() != EOF )

  printf("%d\n", nc);

Said in Christian. This program shows you the length of what is in the standard input.


answered by 03.10.2016 в 10:23