0

我正在开发一个代数应用程序,与图形计算器可以做的非常相似。

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;
}

该程序可以很好地获取系数和幂的商,但是获取变量名存在问题。我认为在 NewQuotient 中的 scanf 语句之后缓冲区中有一个空字符,但如果有,我不知道如何找到它们或如何修复它们。任何帮助表示赞赏。

4

1 回答 1

2

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.

于 2012-07-15T18:23:03.843 回答