Printf vs putchar - different output

I have this simple code (trying to do an exercise in KandR): -

#include <stdio.h>

int main(){
 int c = EOF;

 while(c=(getchar() != EOF)){
   printf("%d",c);
 }

return 0;
}

When I run this and enter any character (single character), I get the output as 11. If I enter several characters, for example, "bbb", I get the output as 1111. I understand that I explicitly added brackets to give an assessment of the status check getchar ()! = EOF, which should either result in 1 or 0. But I don't understand why I get multiple 1.

Another case:

#include <stdio.h>

int main(){
 int c = EOF;

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

return 0;
}

No matter what character I enter, I always get output as a square box with 1 and 0 in it (shown below screenshot)

enter image description here

1) In the first case, why does the output print more than 1 1?

2) Why is not the conclusion of case 2 the same as in case 1?

+4
source share
2 answers

EOF, (getchar() != EOF) true, 1 c. 11, 1 , 1 \n Enter.

, putchar , 1, ( 32), , \n.

while( (c=getchar()) != EOF ){...}   

, , ASCII- ( \n).

+3

1) , 1 1?

EOF. EOF , Ctrl + Z

2) 2 , 1?

%d , putchar . , 'A' printf %d, 65 - ASCII A. , putchar, A.

.

+2

Source: https://habr.com/ru/post/1543767/


All Articles