c - fgets 在没有接受输入的情况下失败

标签 c fgets

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

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

最佳答案

您肯定还有一些先前 I/O 事件遗留下来的'\n'

最好使用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();

关于c - fgets 在没有接受输入的情况下失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23397235/

相关文章:

在 c 中将字符数组转换为 uint32_t 数组——这是正确的方法吗?

c - 如何读取文件、获取数据和计算

c - fgets() 在末尾包含换行符

c - 标准I/O流——fgets()缓冲类型

c - 为什么这个分配做得不好?

c - 这个数组与动态分配的数组有何不同

c - 卡在 connect()

c - 如何纠正循环数组插入中的索引

c - 不将空格识别为循环中的字符?

c - 使用 fscanf 或 fgets 忽略空白?