SummertimeSadness SummertimeSadness - 3 months ago 15
C Question

Wrong scanning in C

My university task is to write a small program, that will calculate quadratic equation, that user enter in this format: ax^2+bx+c=0(for example 3x^2+2x-3=0) . My program have to scan a, b and c and calculate roots of equation. I wrote this to scan coefficients:

scanf("%fx^2+%fx+%f=0", &a, &b, &c);

And its work for equations like this: 2x^2+2x+3=0. But when i have equation with "-" in it(for example 1x^2+1x-2=0) scanning doesnt work correctly. It scan 1 and 1 true, but instead of -2 it scan wrong really big number. Can anyone help me to solve this problem?

Efi Efi

I used 2 chars for the input of the sign, and then I removed them from the last printf float a,b,c; char op1,op2;

scanf("%fx^2%c%fx%c%f=0", &a,&op1,&b,&op2, &c);
if(op1 == '-')
    b *= -1;
    // fix formating for last printf
    op1 = '\b';
if(op2 == '-')
    c *= -1;
    // fix formating for last printf
    op2 = '\b';
printf("a = %f\nb = %f\nc = %f\n",a,b,c);

// if op1 or op2 are '-' it won't be printed
printf("%fx^2%c%fx%c%f=0\n", a,op1,b,op2,c);