1
int main(void) {

    char z;
    while ( (z = getc(stdin)) != EOF) {
        printf("%c", z);
    }

    int  d, flag = 0;
    char c;

    while ((flag = fscanf(stdin, "%d", &d)) != EOF) {
        if (flag == 1) {
            printf("%d", d);
        } else {
            c = getc(stdin);
            printf("%c", c);
        }
    }
return 0;
}

Hi, i have two variations here, there first one is char z which gets the character from input stream and prints it out. it returns exactly what i typed.

The second variation prints out exactly what i type except for the operators '+' and '-'. Kindly enlighten me here. I am confused as multiplication and division works in this variation and not + and -. Below is a screenshot:

Screenshot of the input and output of the above code

Community
  • 1
  • 1
Beanspr0ut
  • 19
  • 2

2 Answers2

0

Because +2 is a valid integer, so it is reading all of that in the fscanf(%d), same with -2, which should be a little more obvious.

So fscanf(%d) reads 1, then on the next iteration, happily reads +2 or -2 as an integer.

The + sign is lost in the output since printf() does not print the sign for positive integers by default.

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
0

The %d format specifier to scanf looks for an integer. Since a + or - preceding some digits is a valid representation of a number, they are read as part of that number.

So when you input 1+2, the 1 gets picked up on the first loop iteration, then +2 gets picked up on the second iteration. When you then print with %d, the leading + is not printed by default.

If you were to input 1-2, you would get the same as output. However instead of reading 1, then -, then 2, it reads 1 then -2. The - still gets printed because it is relevant.

dbush
  • 205,898
  • 23
  • 218
  • 273