0
votes

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?

1
Where is the . period in your claimed input that terminated the loop? Please be precise. Why was the first example "proper" when you entered 2222? - Weather Vane
Your program has undefined behaviour as you compare uninitialized z variable to '.'. It also has UB when the input does not contain the period character. It is also unclear why you expect it to print (not "return", return is a term with its own separate meaning) just one 2 character. - n. 1.8e9-where's-my-share m.
Inside your while loop every key you press adds a character to the keyboard buffer. Then when you press Enter, getchar() reads the first character in the buffer, which also removes it from the buffer. Each successive call to getchar() reads and removes the next char, and so on. Therefore the second version outputs 2222. Your exit condition is if if getchar() encounters a "." it will no longer keep on reading from the buffer. - Module

1 Answers

0
votes

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.