I tested lot's of situations with getchar()
and putchar()
and '\n'
and EOF (in Visual Studio) to understand better how buffering and getchar
works.
If my code
int c;
printf("Enter character\n");
/* 1 - number for explaining steps */
c = getchar();
putchar(c);
/* 2 */
c = getchar();
putchar(c);
printf("hi");
In this code if I enter the character a
and press Enter, it will show
a
hi
This means that when I when press enter the '\n'
will be saved in the buffer too, and then the first item in the buffer (a
) goes to the first c=getchar()
and a
is printed; then the second item in the buffer (\n
) goes to the second
c=getchar()
and prints the new line.
I conclude that '\n'
is saved in the buffer and it's not the result of the command's ability to go to a new line when pressing enter because I tested another code for this:
while ((c = getchar()) != '\n')
putchar(c);
printf("hi");
In this code when I typed a
and press enter it prints ahi
and new line doesn't print it means that when a
passed to getchar()
, putchar()
prints it then when getchar()
gets the '\n'
, the loop terminated and putchar()
inside the loop doesn't print the new line so the command is not the reason for the new line.
Now I want to test another code:
int c;
while ((c = getchar()) != EOF)
putchar(c);
printf("hi");
return 0;
In this one if I pass it abc
and the signal of EOF (in my system ^Z (Ctrl+Z)) it will show abc->
. If we look at it like the previous code:
abc-1(or every thing else shows eof)'\n'
should have been saved in the buffer and first a
go to the first getchar (first time loop works) the b
passes to second getchar then c
passes to the third — and then -1
should have been passed to c=getchar()
and it's against the condition and loop should terminate.
However, instead it prints ->
and loop continued and new line (the last item in the buffer) doesn't print.
Instead when I just ctr +z
when c=getchar()
reads the EOF sign from the buffer the loop terminated and new line printed so why it prints the new line?
It reads the EOF and it should not read anything else in the buffer
in this situation.