Fgets 在 C 编程中运行一次后被忽略?
这就是代码,非常简单,但是为什么在第一个循环之后没有再次提示 fgets
呢?和年龄是。 (奇怪的是,它与 scanf("%s",&name_temp)
一起使用,但我也需要抓取其他字符,例如 áéíóúÇ、空格,所以使用 fgets
会更好>)
int menu_option = 0;
char name_temp[80] = "";
int age_temp = 0;
while(menu_option != 9){
//strcpy(name_temp,"");
printf("Type your name\n");
fgets(name_temp, 80, stdin);
printf("\nType your age\n");
scanf("%d", &age_temp);
}
(从已删除的答案中移出)
感谢你们的回答,但我认为你们没有理解我的问题,测试我发送的代码,然后你们会看到而不是出现在终端中供您输入的内容,在第一个 while 循环之后它会被忽略。
我想要的是,在第一个循环(while)之后,它返回并再次询问该人的姓名,并且使用该程序的人必须再次输入。但取而代之的是,在第一次循环之后,它只是不要求您输入任何内容, fgets 被完全忽略。
请尝试该代码并说出我能做什么。
我尝试了 freopen 的东西,但没有用。
So this is the code, its pretty simple, but why isn't the fgets
prompted again after the first loop? and age is. (And weirdly it works with scanf("%s",&name_temp)
but I need to grab other characters too like áéíóúÇ, spaces, so it would be better with fgets
)
int menu_option = 0;
char name_temp[80] = "";
int age_temp = 0;
while(menu_option != 9){
//strcpy(name_temp,"");
printf("Type your name\n");
fgets(name_temp, 80, stdin);
printf("\nType your age\n");
scanf("%d", &age_temp);
}
(moved from the deleted answer)
Guys thanks for your answers, but I don't think you guys understood my question, test this code that I sent, and you will see that instead of appearing the thing in the Terminal for you to type, it is just ignored after the first while loop.
What I wanted is that after the first loop (while) it came back and asked again the name of the person and the person using the program would have to type again. but instead of that, after the first time of the loop, it just doesn't ask for you to type anything, the fgets is completely ignored.
please try the code and say what can I do.
I tried the freopen thing and did not work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当我运行它时,它确实每次通过循环打印出“键入你的名字”,但没有等待输入,因为它正在获取对 scanf 的调用留在输入流上的 '\n' 。这是一个常见问题;一种解决方案是插入 getchar();在循环的底部,吃掉换行符。
When I ran it, it did indeed print out "Type your name" each time through the loop, but did not wait for input, because it was getting the '\n' which the call to scanf left on the input stream. This is a common problem; one solution is to insert getchar(); at the bottom of the loop, to eat that newline.
fgets
读取一行,即读取stdin
直到到达\n
字符。scanf
将\n
字符保留到stdin
中。然后,
fgets
读取一个空行。fgets
read a line, that is, it readstdin
until\n
character is reached.scanf
left the\n
character intostdin
.Then,
fgets
read an empty line.我希望我能回答你的问题。
我发现有效的方法是将这一行添加到循环中。
尤其是之后
I hope I answer your question.
What I found to work is to add this line in the loop.
more especially after
您应该以二进制模式打开
stdin
。使用 freopen(NULL, "rb", stdin) 来执行此操作。有关更多详细信息,请参阅 C 读取二进制 stdin。
You should open
stdin
in binary mode. Usefreopen(NULL, "rb", stdin)
to do this.See C read binary stdin for more details.