这里是 C 初学者。我正在尝试运行一个循环,将字符串和ints
输入到struct
. 当提示输入“姓氏”时,用户可以在没有其他输入的情况下按回车键,循环应该结束。
问题是,使用此代码,循环不会结束(姓和名输入请求一起在同一行上运行)并且薪水的值总是错误的(0 或某个大数字)
while (employee_num <= 2)
{
printf("Enter last name ");
fgets(employee[employee_num].last_name, sizeof(employee[employee_num].last_name), stdin);
if(strlen(employee[employee_num].last_name) == 0)
break;
printf("Enter first name ");
fgets(employee[employee_num].first_name, sizeof(employee[employee_num].first_name), stdin);
printf("Enter title ");
fgets(employee[employee_num].title, sizeof(employee[employee_num].title), stdin);
printf("Enter salary ");
fgets(strng_buffer, 1, stdin);
sscanf(strng_buffer, "%d", &employee[employee_num].salary);
++employee_num;
getchar();
}
如果我改为尝试此代码,我可以在第一次运行后正确退出循环,但之后无法退出(通过在姓氏部分按 enter - 也许是 \n 我似乎无法清除?):
char strng_buffer[16];
while (employee_num <= 5)
{
printf("Enter last name ");
fgets(strng_buffer, sizeof(strng_buffer), stdin);
sscanf(strng_buffer, "%s", employee[employee_num].last_name);
if(strlen(employee[employee_num].last_name) == 0)
break;
printf("Enter first name ");
fgets(strng_buffer, sizeof(strng_buffer), stdin);
sscanf(strng_buffer, "%s", employee[employee_num].first_name);
printf("Enter title ");
fgets(strng_buffer, sizeof(strng_buffer), stdin);
sscanf(strng_buffer, "%s", employee[employee_num].title);
printf("Enter salary ");
scanf("%d", &employee[employee_num].salary);
++employee_num;
getchar();
}
我很好奇如何使这项工作按预期进行,以及此类条目的最佳实践是什么(即使用 sscanf、fgets 等)
提前致谢!