-4
#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?

Jens
  • 69,818
  • 15
  • 125
  • 179
secret
  • 1
  • 1
  • 2
    Of course. You press [Enter] which generates an `'\n'` which is read with `getchar()` into `c` and you then test `while (c != EOF)` (forever). Adding the additional line attempts an additional input stopping the infinite loop (you could press `ctrl+d`, or `ctrl+z` - on windows to generate a manual `EOF` -- but see [CTRL+Z does not generate EOF in Windows 10](http://proc-x.com/2017/06/ctrlz-does-not-generate-eof-in-windows-10/)) – David C. Rankin Jun 02 '18 at 07:08
  • 1
    Resd this article: https://en.m.wikibooks.org/wiki/C_Programming/stdio.h/getchar – danglingpointer Jun 02 '18 at 07:09
  • 1
    Why do you expect the second example to print a single `A` only? – melpomene Jun 02 '18 at 08:43

1 Answers1

0

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.

Achal
  • 11,821
  • 2
  • 15
  • 37