I do not understand very well how getchar
and putchar
works, for example:
main()
{
double nc;
for (nc=0; getchar() != EOF; ++nc)
;
printf("%.0f\n", nc);
}
I do not understand very well how getchar
and putchar
works, for example:
main()
{
double nc;
for (nc=0; getchar() != EOF; ++nc)
;
printf("%.0f\n", nc);
}
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;
printf("%c",c);
}
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:
nc
. Note that nc
is independent of getchar
. nc
. A slightly more readable version could be:
main()
{
int nc = 0; // Para enteros mejor int
while( getchar() != EOF )
nc++;
printf("%d\n", nc);
}
Said in Christian. This program shows you the length of what is in the standard input.
Greetings.