I have written the following simple C code, which compiles and runs fine. However it behaves in a way that I don't understand. I type a character, it prints it on the screen. But when I press the return key it prints the whole line. So if I type the letters a, b and c, abc is printed on the command line twice. WHy does it do this?
#include <stdio.h>
int main(){
int c;
while((c=getchar())!=EOF){
putchar(c);
}
return 0;
}
It's your terminal, not the program.
When you press a key, your terminal prints it, but doesn't pass it to the program.
When you press enter, the terminal pass the whole line to the program, and the program prints the line.
EDIT: if you use Unix/Linux/etc, you can write stty -icanon -echo
to disable that terminal behavior.
The -echo
turns off the printing, and the -icanon
turns off the buffering.