Aj_76
Aj_76

Reputation: 39

Strange Execution within function in C

I'm working on an algebra application, very similar to what graphing calculators can do.

struct quotient NewQuotient()
{
    struct quotient temp;
    printf("Enter the numerator\n");
    scanf("%d", &temp.numerator);
    printf("Enter the denominator\n");
    scanf("%d", &temp.denominator);
    return temp;   
}

char NewVarname()
{
    char temp;
    printf("Enter the variable letter: \n");
    scanf("%c", &temp);
    return temp;
}

struct term NewTerm()
{
    struct term temp;
    printf("Enter the coefficient: ");
    temp.coefficient = NewQuotient();
    printf("Enter the variable name: \n");
    temp.varname = NewVarname();
    printf("Enter the power: ");
    temp.power = NewQuotient();
    return temp;
}

The program gets the quotients for the coefficiant and powers just fine, but there's a problem with getting the variable name. I'm thinking there's a null character stuck in the buffer after the scanf statements in NewQuotient but if there are are, I don't know how to find them or how to fix them. Any help is appreciated.

Upvotes: 0

Views: 145

Answers (1)

anatolyg
anatolyg

Reputation: 28241

In general, scanf doesn't go well with gets. It's not easy to use both in the same program. In your case, scanf reads exactly one character (x), while the user inputs 2 characters - x and end-of-line.

The end-of-line character remains in the input buffer, causing the following. gets reads the input until the nearest end-of-line character, which in your case appears to arrive immediately, even while the user doesn't have time to input anything.

To fix this, do all your input with either gets or scanf:


First option

struct term NewTerm()
{
    ....
    // Old code:
    // scanf("%c", &temp.varname);

    // New code, using gets:
    char entry[MAX];
    gets(entry);
    temp.varname = entry[0];
    ....
}

Second option

struct quotient NewQuotient()
{
    ....
    // Old code
    // gets(entry);

    // New code, using scanf:
    int x, y;
    scanf("%d/%d", &x, &y);
    ....
}

BTW if you choose the first option, you should use fgets instead of gets.

Upvotes: 2

Related Questions