Question

J'ai écrit le code C simple ci-dessous, qui compile et fonctionne bien.Cependant, il se comporte de manière à ce que je ne comprenne pas.Je tape un personnage, il l'imprime à l'écran.Mais Lorsque j'appuie sur la touche de retour, il imprime la ligne entière .Donc, si je tape les lettres A, B et C, ABC est imprimé deux fois sur la ligne de commande.Pourquoi cela fait-il cela?

#include <stdio.h>


int main(){


    int c;
    while((c=getchar())!=EOF){
        putchar(c);
    }

return 0;

}

Était-ce utile?

La solution

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.

Autres conseils

Because your terminal is line buffered.

It doesn't send data to your program until it encounters a newline, though it will echo the character to the screen so you can see they key you hit.

What you are seeing is a combination of a few things.

  1. When you type a character, unless you expressedly stop it from happening, it will print to the screen.
  2. Most print statements won't actually print anything until a new line is printed.

So, the text you are seeing is coming from the type commands, but the putchar() string printed is happening all at once.

You're reading from the standard input stream which is line buffered.

Try this alternate code and you'll understand better what is going on:

#include <stdio.h>
int main(){
    int c;
    while((c=getchar())!=EOF){
        printf("got char %c\n", c);
    }
    return 0;
}

You need non-line buffered input. This is going to depend on your platform, but here is an answer on Linux: non-buffering stdin reading

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top