Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

-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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading