Trying to understand printf, getchar and putchar behavior
Hello!
I'm trying to understand text input and ouput in C by using the next piece of code:
Code:
/*EOF is found at stdio.h file as a symbolic constant,
specifically as #define EOF (-1)*/
main()
{
int c;
long counter = 0;
while((c = getchar()) != EOF){
++counter;
printf("%ld",counter);
}
printf("\nEnd of loop\n");
}
When running the program, I use characters asd as text input, it does nothing until enter key is pressed, then the terminal outputs:
which I think is the count of the number of iterations done before next line(enter) value is used as input, the program continues until EOF is the input.
By adding putchar(c); into the loop:
Code:
/*EOF is found at stdio.h file as a symbolic constant,
specifically as #define EOF (-1)*/
main()
{
int c;
long counter = 0;
while((c = getchar()) != EOF){
putchar(c);
++counter;
printf("%ld",counter);
}
printf("\nEnd of loop\n");
}
Again when running I use characters asd as text input, after pressing enter key, the terminal outputs:
Why does it always waits until the text line is finished?.
I'm not a experienced programmer, but I thought that with the last code, the terminal will echoe every character used as input (printchar(c);) together with the iteration number (printf("%ld",counter);).
In example, if input is character a, the output will be printed instantly without waiting for next line value:
not requiring next line to produce:
There must be a reason of this behavior, but I ignore the point.
Sorry for the beginner question & thanks for reading! :)