views:

246

answers:

1

I'm learning basics of C and writing a simple first order equation solver. I want the input to be exactly ax+b=c or ax-b=c, where a, b, c are double type. I'm employing scanf() to read in user input and to check if it's of the correct form. However, if I enter a negative double, -4.6 say, as the "a" in the equation, scanf() won't read the a,b,c correctly. I'm using %lf inside scanf(). How do I read a negative double, then? Many thanks.

My code:

#include <stdio.h>
int main(void)
{
    double a,b,c,x;
    printf("Enter the expression:\n");
    if (scanf("%lfx%lf=%lf", &a, &b, &c) == 3)
    {
    x = (c - b)/a;
    printf("x=%.2f\n", x);
    }
    else if (scanf("%lfx+%lf=%lf", &a, &b, &c) == 3)
    {
        x = (c - b)/a;
        printf("x=%.2f\n", x);
    }
    else
        printf("Invalid expression\n");
    return 0;

}

+2  A: 

One of the difficulties with using scanf() directly (instead of, say, fgets() and sscanf()) is working out where it got to when it went wrong.

You could also help yourself by noting that scanf() returns the number of successful conversions. You should be testing:

if (scanf("%lfx+%lf=%lf", &a, &b, &c) != 3)
    ...something went wrong...
else
   ...more code using successfully read data...

What you've got should work OK as long as the data is correct and you don't encounter EOF. That is, the call is well formed; the context in which it occurs may not so clean.

Also, since you want to allow either '+' or '-' between the two terms, you really need to move towards a tokenizing mechanism that reads the next token (a possibly negative number, an 'x', a '+' or '-', and another (possibly negative) number). You can then interpret these. Using scanf() is a disaster if the user entered '-2.3x-4.5=9.1', then when the scan fails on on the (second) '-', you have no way to go back and reread the whole data with the negative format. Or you need to read the separator symbol '+' or '-' into a char value.

Jonathan Leffler
Thank You. My problem was solved as I read your answer and realized that what I'm doing is trying to go back / reread the user input in case my first scanf() fails. As that's not possible, using your hint on using a char variable to read the sign preceeding b solved the problem.
rize