gpt4 book ai didi

c - scanf 获取之前执行的 getchar() 的输入

转载 作者:太空宇宙 更新时间:2023-11-04 04:02:16 24 4
gpt4 key购买 nike

我使用 getchar() 来读取字符并将它们放在表中,以及使用 scanf 来获取整数。

scanf() 的问题在于它不等待用户输入,而是使用 getchar() 从缓冲区中读取上一行给出的最后一个字符。

我尝试了 sscanf、fflush(stdin);等等,但我仍然有同样的行为。

#include <stdio.h>
#include <stdlib.h>


main()
{
int i, choice, tmp_day, tmp_month;
char name[5];

printf("insert choice(1-3):\n");
scanf("%d",&choice);


printf("name: ");
for (i=0;i<5;i++) name[i]=getchar();

name[5] = '\0' ;

printf("day (1-31): ");

scanf("%d",&tmp_day);

printf("month (1-12): ");

scanf("%d",&tmp_month);

printf("\n%d %d", tmp_day, tmp_month);

}

有什么想法吗?

提前致谢。

最佳答案

关于不一定可移植的 fflush(stdin) 的详细讨论。

http://c-faq.com/stdio/gets_flush2.html

关于c - scanf 获取之前执行的 getchar() 的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10344120/

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