我正在尝试输入结构数组的名称。虽然这对于第一次迭代工作正常,但在第二次迭代中,结构对象的 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/