【问题标题】:fgets falls through without taking inputfgets 在没有输入的情况下失败
【发布时间】:2014-05-01 06:24:42
【问题描述】:

每当我调用此函数时,它都无法让用户有机会输入字符串。不知道为什么很确定我的语法是正确的。认为我与换行符有关,但我不知道如何摆脱它

 void serchName(dealers_t *ptr, int numDealers)
{
    char dealerName[NAME_LEN];
    int index;

    printf("please enter the dealer's name:");
    fgets(dealerName, sizeof(dealerName), stdin);
    system("PAUSE");

    for (index = 0; index < numDealers; index++, ptr++)
    {
        if (strcmp(dealerName, ptr->name) == 0)
        {
            printf("MATCH FOUND:%s\n%s\n%s\n%i\n%s\n", ptr->name,ptr->city,ptr->state,ptr->zip,ptr->phone);
        }
    }
}

【问题讨论】:

  • 你在通话前的标准输入中有一些东西。确保你不这样做。
  • fflush(stdin);也许?
  • @Jim 仅当您想要未定义的行为时。
  • scanf("%c%*c", &ch); /* 避免刷新标准输入 */
  • Fgets 还将终端 '\n' 读入缓冲区,因此 strcmp() 将失败(除非 ptr->name 的末尾也有 '\n')

标签: c fgets


【解决方案1】:

您肯定有一些 '\n' 之前的 I/O 活动遗留下来的。

最好在同一程序中使用fgets(),不要与scanf() 混合使用。

但由于我看不到其他代码,建议使用以下内容以消耗剩余的'\n'

printf("please enter the dealer's name:");
int ch;
ch = fgetc(stdin);
if (ch != '\n') ungetc(ch, stdin);
if (fgets(dealerName, sizeof(dealerName), stdin) == NULL) Handle_EOForIOError();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多