【问题标题】:Strange Execution within function in CC中函数内的奇怪执行
【发布时间】:2012-07-15 16:11:52
【问题描述】:

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

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

【问题讨论】:

  • 不应该scanf("%c", temp.varname); 是scanf("%c", &(temp.varname)); 吗?
  • 你为什么在一个地方使用gets()而在另一个地方使用scanf()?除此之外,如果您要突出显示您输入的部分,以便更容易区分,这可能会有所帮助。
  • @Aj_76 我根据我的理解格式化了问题;如果我猜错了,请回复和/或澄清。
  • 如果我使用 printf("%s", entry),它最终会转储核心。谢谢anatolyg,我忘了说清楚输入/输出。重要的是程序提示输入电源,但用户没有机会输入任何内容
  • 不要使用gets() 或scanf()。使用 fgets()。您的应用程序可能不会像这样更改,但这是一个很好的做法。它将使您免于所有未来的缓冲区溢出错误和头发撕裂。

标签: c function structure


【解决方案1】:

一般来说,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。

【讨论】:

  • 全部改成printf后执行问题还是一样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
相关资源
最近更新 更多