c - fgets() 将\n 提供给后续字符串,而不接受输入

标签 c structure

我正在尝试输入结构数组的名称。虽然这对于第一次迭代工作正常,但在第二次迭代中,结构对象的 name 字符串收到 \n ,我不知道为什么会这样。

我也尝试过 fflush(stdin),但似乎不起作用:/

struct employee
{
    char ac_no[20], name[30];
    float balance;
};

void getdata (struct employee *);
void getdata(struct employee *ptr)
{
    printf("Enter Name: ");
    fgets(ptr->name, 29, stdin);
    ptr->name[strcspn((ptr->name), "\r\n")] = 0;
    printf("Enter Account Number: ");
    fgets(ptr->ac_no, 19, stdin);
    printf("Enter Balance: ");
    scanf_s("%f", &(ptr->balance));
    fflush(stdin);
}

//In Main()
struct employee emp[5];
register int i;
for (i = 0;i < 5;i++)
{
    printf("\nEmployee %d: \n", (i+1));
        getdata(&emp[i]);
}

最佳答案

scanf不消耗\n ,所以\n仍在 stdin并由 fgets 阅读在下一次迭代中。 fflush(stdin)不在标准 C 中,因此行为未定义。

您可以在 scanf_s 之后使用换行符使用getc :

...
fgets(ptr->ac_no, 19, stdin);
printf("Enter Balance: ");
scanf_s("%f", &(ptr->balance));
getc(stdin);

关于c - fgets() 将\n 提供给后续字符串,而不接受输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35451627/

相关文章:

c - C语言中如何从数组中随机选取元素?

C fscanf 输入验证

c++ - 在 C++ 中创建堆上的结构数组

java - 在 Android 应用程序上初始化后 CircularFifoBuffer 崩溃

python - 如何以 Pythonic 方式停止 try/except 中 for 循环的代码执行?

Python 3.5 ctypes libc printf() 仅打印字符串的第一个字节 Windows 7/10

c - 归并排序 C 实现

C释放结构指针成员

mysql - MySQL 的数据库替代品可用于数百万个表

c - 函数指针混淆