gpt4 book ai didi

c - gets() 在 while 循环中只接受一次输入

转载 作者:太空狗 更新时间:2023-10-29 16:08:16 26 4
gpt4 key购买 nike

我是 C 的新手,正在完成一些练习,但在 while 循环中使用 gets() 时遇到问题。在搜索中,我认为它可能与\n 字符有关,但我希望有人能够对这里发生的事情进行更彻底的解释:

这个循环只会运行一次——它会第二次将“输入姓氏”打印到屏幕上,然后在 gets() 有机会第二次接受任何输入之前退出循环:

while (employee_num <= 10)
{
printf("Enter last name ");
gets(employee[employee_num].last_name);
if(strlen(employee[employee_num].last_name) == 0)
break;
printf("Enter first name ");
gets(employee[employee_num].first_name);
printf("Enter title ");
gets(employee[employee_num].title);
printf("Enter salary ");
scanf("%d", &employee[employee_num].salary);
++employee_num;
}

提前致谢!

最佳答案

读取薪水后,输入缓冲区中会有一个换行符 (\n)。这是在第二次迭代中被选为姓氏的。您可以通过在最后一次 scanf 之后添加 getchar() 来忽略它:

while (employee_num <= 10) {
...
printf("Enter salary ");
scanf("%d", &employee[employee_num].salary);
++employee_num;
getchar();
}

关于c - gets() 在 while 循环中只接受一次输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14465713/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com