Search code examples
cgetcharputchar

Functions putchar and getchar


Can anyone help me to figure out how these functions work.
There are two pieces of code - with and without a while loop.

#include <stdio.h>
int main(void) 
{
char z;
z = getchar();
putchar (z);
}

The second one is

#include <stdio.h>
int main(void)
{
char z;
while (z != '.')
{
z = getchar();
putchar(z);
}
}


The problem is that the first one is working properly, while the second one returns all the characters it gets (e.g. if the input was 2222, the function returns 2222). Why didn't it return 2?


Solution

  • The two versions are different.

    In the first version you read a single char and write it.

    In the second you keep reading a char and writing it, until the char is a period. Note that the period will be read and written. Only the following pass is ignored. There is a caveat, though. You did not initialize z. Depending on the compiler it may be automatically initialized to \0. Otherwise, you are facing undefined behavior.