因此,我编写了一个简单的C程序,该程序循环读取一些信息,然后询问用户输入的内容是否正确,但最后一个输入(y \ n)从未从控制台变为红色。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char *name=malloc(sizeof(char)*20),*surname=malloc(sizeof(char)*20),awnser,c;
int age,tries=1;
while(1){
printf("try %d\n",tries++);
printf("enter name: ");
fgets(name,19,stdin);
strtok(name,"\n");
printf("enter surname: ");
fgets(surname,19,stdin);
strtok(surname,"\n");
printf("enter age: ");
scanf("%d",&age);
printf("so you are %s %s %d years old? (y/n)\n",name,surname,age);
awnser=getchar();
if(awnser=='y'){
break;
}
}
free(surname);
free(name);
}
预期输出:
try 1
enter name: bill
enter surname: mpris
enter age: 344
so you are bill mpris 344 years old? (y/n)
n
try 2
enter name: bill
enter surname:
moris enter age: 34
so you are bill moris 34 years old? (y/n)
y
程序输出:
try 1
enter name: bill
enter surname: moris
enter age: 34
so you are bill moris 34 years old? (y/n)
try 2
enter name:
有人知道为什么会这样吗?我尝试将fflush(stdin)放在每个fget之后,但是我仍然遇到相同的错误。我可以想象它与缓冲区有关,并且某些字符(可能是'\ n')正在被读取,但是getchar