Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output for the following C code is confusing me [closed]

Tags:

c

This is my code

#include <stdio.h>
main()
{
    int c;
    c=getchar();
    while(c!=EOF)
    {
        int x;
        x=(c!=EOF);
        printf("%d",x);
        putchar(c);
        c=getchar();
    }
}

Output (When I enter A):

A
1A1

Why is it not 1A only. Why is it repeating 1.Like first the program will take the value of c from getchar. Then it will go inside the loop. When condition will be true it will print the value of x and then value of c. Then again it should ask me for an input. Instead it is displaying another 1 then asking for the input. Kindly help.

like image 459
Ritvik Sinha Avatar asked Dec 14 '22 11:12

Ritvik Sinha


2 Answers

It is because you entered A and <enter>. The <enter> produces the second 1.

You can press CTRL + D on unix or CTRL + Z on Windows to close the stdin of the program instead of pressing <enter>. This will give you the expected output.

With the <enter>: https://ideone.com/lWJ3Xz

and without: https://ideone.com/QsXiYz

like image 133
mch Avatar answered Jan 11 '23 23:01

mch


a minimum debug effort and you will know yourself.

printf("FEOF=%d, C=0x%x\n",x,c);

like image 43
0___________ Avatar answered Jan 12 '23 01:01

0___________