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
.
solved not able to understand the role of getchar and putchar here