更新时间:2023-11-18 08:39:28
如果冲洗STD不工作,然后尝试读取多余的字符和丢弃,所建议的这里。
这将工作:
的#include<&string.h中GT;
#包括LT&;&stdio.h中GT;诠释主(){
焦农布雷[10];
烧焦mensaje [80];
焦炭℃; 的printf(键入您的姓名:\\ n);
scanf函数(%S,农布雷); 而((C =的getchar())='\\ n'和;!&安培;!C = EOF)
/ * *丢弃/; 的printf(现在,键入一条消息:\\ n);
得到(mensaje); 的printf(%S:%S,农布雷,mensaje);
返回0;
}
After wasting too much time searching why my program doesn't execute gets() after using scanf(), I found a solution which is to use fflush(stdin) after scanf() to enable gets() to get a string.
The problem is that fflush(stdin) doesn't do what is expected from it: The program continues skipping gets() and I can't write any phrase in the console to be read.
My code is the next one:
#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;
}
If flushing std doesn't work, then try reading in the extra characters and discarding, as suggested here.
This will work:
#include <string.h>
#include <stdio.h>
int main(){
char nombre[10];
char mensaje[80];
char c;
printf("Type your name:\n");
scanf("%s", nombre);
while((c= getchar()) != '\n' && c != EOF)
/* discard */ ;
printf("Now, type a message:\n");
gets(mensaje);
printf("%s:%s",nombre,mensaje);
return 0;
}