C中函数内的奇怪执行

时间:2012-07-15 16:11:52

标签: c function structure

我正在研究代数应用程序,与图形计算器的功能非常相似。

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语句之后,缓冲区中有一个空字符,但如果有,我不知道如何找到它们或如何修复它们。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

一般来说,scanfgets的关系并不顺畅。在同一个程序中使用它们并不容易。在您的情况下,scanf只读取一个字符(x),而用户输入2个字符 - xend-of-line

end-of-line字符保留在输入缓冲区中,导致以下内容。 gets读取输入,直到最近的end-of-line字符,在您的情况下,即使用户没有时间输入任何内容,也会立即到达。

要解决此问题,请使用getsscanf

完成所有输入

第一个选项

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

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

第二个选项

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

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

如果您选择第一个选项you should use fgets instead of gets,则为BTW。