Search code examples
cgetcharputchar

not able to understand the role of getchar and putchar here


#include <stdio.h>
#include <stdlib.h>

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

when I compile and give input ABC and then press enter, the never ending loop starts like AAAAAAAAA....

And now look at this code below

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int c;
    c = getchar();
    while (c != EOF) {
         putchar(c);
         c = getchar ();   // added this single line 
    }
    return 0;
}

In this program, when I input ABC, the output is ABC. Can anyone please explain why it is not showing just a single A as output?


Solution

  • Look at the below code you mentioned

    int main(void){
            int c;
            c = getchar();
            while (c != EOF) {
                    putchar(c);
    
            }
            return 0;
    }
    

    When c = getchar(); executes & if you provided input as ABC at runtime & press ENTER(\n), that time c holds first character A. Next come to loop, your condition is c!=EOF i.e A!=EOF which always true & it will print A infinitely because you are not asking second time input so c holds A.

    correct version of above code is

    int main(void){
            int c;
            while ( (c = getchar())!=EOF) { /* to stop press ctrl+d */
                    putchar(c);
            }
            return 0;
    }
    

    case 2 :- Now looks at second code

    int main(void){
            int c;
            c = getchar(); 
            while (c != EOF) { /*condition is true */
                    putchar(c);  
                    c = getchar ();/*After printing ABC, it will wait for second input like DEF, unlike case-1  */ 
            }
            return 0;
    }
    

    Can anyone please explain why it is not showing just a single A as output ? Why it should prints only A, it prints whatever input you given like ABC & so on. Just note that getchar() works with buffered input i.e when you press ENTER getchar() will read upto that & when there is nothing left to read getchar() returns EOF.