Fgets跳过输入
我试过环顾四周,似乎无法找到错误所在。 我知道它必须与我使用fgets的方式有关但我无法弄清楚它的生命是什么。 我已经读过混合fgets和scanf会产生错误,所以我甚至将我的第二个scanf更改为fgets,它仍会跳过其余的输入,只打印第一个。
int addstudents = 1; char name[20]; char morestudents[4]; for (students = 0; students<addstudents; students++) { printf("Please input student name\n"); fgets(name, 20, stdin); printf("%s\n", name); printf("Do you have more students to input?\n"); scanf("%s", morestudents); if (strcmp(morestudents, "yes")==0) { addstudents++; } }
我的投入是乔,是的,比尔,是的,约翰,不。 如果我使用scanf代替第一个fgets,所有都按计划进行,但我希望能够使用包含空格的全名。 我哪里错了?
当程序显示Do you have more students to input?
然后输入yes
然后在控制台上按Enter键,然后\n
将存储在输入流中。
您需要从输入流中删除\n
。 要做到这一点,只需调用getchar()
函数。
如果你不混合scanf
和fgets
会很好。 scanf
有很多问题,更好地使用fgets
。
为什么每个人都说不使用scanf? 我该怎么用?
试试这个例子:
#include #include int main (void) { int addstudents = 1; char name[20]; char morestudents[4]; int students, c; char *p; for (students = 0; students