Code doesn't take three inputs and display three different results but takes one input and displays the same result three times

Advertisements

I’m just beginning to learn c and I’m confused about why my code only takes one input and displays the same result three times when it’s supposed to take three inputs and display three different results. This is my code:

#include <stdio.h>

int main(){
    int a, b, c, d, result[3];
    
    for(int i=0; i<3; i++){
    scanf("(%d+%d)x(%d-%d)", &a, &b, &c, &d);
    result[i] = (a+b)*(c-d);
    }
    
    printf("%d %d %d\n", result[0], result[1], result[2]);
    
    
    return 0;
}

It’s supposed to take the inputs

(3+4)x(1-3)
(8+3)x(5-4)
(4+12)x(11-9)

and output

-14 11 32

Instead it only takes

(3+4)x(1-3)

and outputs

-14 -14 -14

What am I doing wrong?

>Solution :

You need to skip the new line character '\n' between the inputs that corresponds to the pressed key Enter by placing a leading space in the format string

scanf(" (%d+%d)x(%d-%d)", &a, &b, &c, &d);
      ^^^

In general you should check whether a call of scanf was successful.

Leave a ReplyCancel reply