JCo*_*der 1 c gets scanf fflush
在使用scanf()之后浪费了太多时间搜索为什么我的程序没有执行gets(),我找到了一个解决方案,即在scanf()之后使用fflush(stdin)来启用gets()来获取字符串.
问题是fflush(stdin)没有做到它所期望的:程序继续跳过gets(),我不能在控制台中写任何短语来读取.
我的代码是下一个:
#include <string.h>
#include <stdio.h>
int main(){
char nombre[10];
char mensaje[80];
printf("Type your name:\n");
scanf("%s", nombre);
fflush(stdin);
printf("Now, type a message:\n");
gets(mensaje);
printf("3/%s:%s",nombre,mensaje);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果刷新std不起作用,那么尝试读取额外的字符并丢弃,如此处所示.
这将有效:
#include <string.h>
#include <stdio.h>
int main(){
char nombre[10];
char mensaje[80];
int c;
printf("Type your name:\n");
scanf("%9s", nombre);
while((c= getchar()) != '\n' && c != EOF)
/* discard */ ;
printf("Now, type a message:\n");
gets(mensaje);
printf("%s:%s",nombre,mensaje);
return 0;
}
Run Code Online (Sandbox Code Playgroud)