我正在研究代数应用程序,与图形计算器的功能非常相似。
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语句之后,缓冲区中有一个空字符,但如果有,我不知道如何找到它们或如何修复它们。任何帮助表示赞赏。
答案 0 :(得分:2)
一般来说,scanf
与gets
的关系并不顺畅。在同一个程序中使用它们并不容易。在您的情况下,scanf
只读取一个字符(x
),而用户输入2个字符 - x
和end-of-line
。
end-of-line
字符保留在输入缓冲区中,导致以下内容。 gets
读取输入,直到最近的end-of-line
字符,在您的情况下,即使用户没有时间输入任何内容,也会立即到达。
要解决此问题,请使用gets
或scanf
:
第一个选项
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。