No cache version.

Caching disabled. Default setting for this page:enabled (code LNG204)
If the display is too slow, you can disable the user mode to view the cached version.

getchar/putchar: Copieur...

Le but de ce programme est de recopier sur le canal standard de sortie ce qui se présente par le canal d'entrée standard.

Il fonctionne de cette manière:

  • Lecture d'un caractère.
  • Tant que le caractère n'est pas le signal de fin de fichier:
    • Sortir le caractère lu.
    • Lire un nouveau caractère.
  1. #include <stdio.h>
  2.  
  3. void main (void)
  4. {
  5. int c;
  6. c=getchar();
  7. while (c!=EOF)
  8. {
  9. putchar (c);
  10. c=getchar();
  11. }
  12. }

Résultat

Je copie cette ligne
Je copie cette ligne
-

Si nous introduisons la caîne de caractères suivante : "Je copie cette ligne", au moment de valider la ligne par la touche [Enter], la ligne est intégralement recopiée...

Remarques copy1.c

  • L'opérateur de relation != signifie "est différent de".
  • Attention : l'utilisation de EOF (End Of File) est interprétée de différentes manières (égal à 0 ou à -1).
    Nous pouvons donc définir la valeur de EOF comme constante au début du programme de cette manière: #define EOF -1 ou bien: #define EOF 0 afin de s'assurer que EOF sera bien interpreté.
  • Nous pouvons réduire le nombre d'instructions en positionnant la saisie du caractère dans la condition de la boucle while, ce qui nous amène au code du programme suivant : copy2.c...
  1. #include <stdio.h>
  2.  
  3. void main (void)
  4. {
  5. int c;
  6. while ((c=getchar())!=EOF)
  7. {
  8. putchar (c);
  9. }
  10. }

Remarques copy2.c

  • Profitons de ce programme pour nous rappeler l'importance des parenthèses...
    En effet, (c=getchar())!=EOF est différent de c=(getchar()!=EOF). Ce dernier affecte la valeur 0 ou 1 à la variable c selon que getchar rencontre ou non la fin de fichier.

English translation

You have asked to visit this site in English. For now, only the interface is translated, but not all the content yet.

If you want to help me in translations, your contribution is welcome. All you need to do is register on the site, and send me a message asking me to add you to the group of translators, which will give you the opportunity to translate the pages you want. A link at the bottom of each translated page indicates that you are the translator, and has a link to your profile.

Thank you in advance.

Document created the 02/01/2003, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/c-getchar-putchar.html

The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.