在浪费太多时间搜索为什么我的程序在使用 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;
}
最佳答案
如果刷新 std 不起作用,则按照建议尝试读入多余的字符并丢弃 here .
这会起作用:
#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;
}
关于c - 程序在 scanf() 之后不执行 gets(),即使使用 fflush(stdin),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22226529/