Search code examples
cscanffractions

How to read both mixed fraction and normal fraction?


How do I read both mixed numbers and fractions from stdin? For example:

int whol, num, den;

scanf("%d %d/%d", &whol, &num, &den);

However, if the user wants to enter a non-mixed fraction, he has to put a "0" in the beginning.

How can I allow both forms: %d/%d and %d %d/%d ?

Maybe I shouldn't be using scanf() for this?


Solution

  • A preferred practice is to first read an entire line into a buffer first, and then parse it. For example,

    char buf[80];
    char dummy[80];
    // ...
    if (!fgets(buf, sizeof buf, stdin) {
        // handle error
    }
    else if (sscanf(buf, "%d%d/%d%s", &whol, &num, &den, dummy) == 3) {
        // ... handle mixed fraction
    }
    else if (sscanf(buf, "%d/%d%s", &num, &den, dummy) == 2) {
        // ... handle normal fraction
    }
    else {
        // ... error, bad input
    }
    

    The extra array dummy, which is never used, helps insure the complete input line is parsed.