[英]The fgets function doesnt save the first letter in the string
我写了一个程序,它从用户那里得到一个数字,然后从用户那里得到每个数字的名字......例如,如果用户输入数字10,它需要10个名字并将它放在一个数组中结构......一切都很好,除了当我打印名字时,它跳过第一个字母......就像我输入“Amit”这个名字一样,它打印出“mit”......,我输入的最后一个字符串根本没有保存。这是我写的:
const number_candidates; // Getting the number of candidates
#define MAX 256
#define min_candidate 10
#define max_candidate 60000
typedef struct candidate // Getting details for each candidate
{
char name[MAX];
int sing_grade;
int per_grade;
int cam_grade;
int sharmanti_grade;
}candidate;
void get_details_candidates(candidate candidate[MAX])
{
int i = 0;
printf ("\n");
for (i = 0 ; i < number_candidates ; i++)
{
printf ("Please enter the %d name: ", i + 1);
fgets (candidate[i].name, MAX, stdin);
getchar();
}
}
这是印刷:
for (i = 0 ; i < number_candidates ; i++)
{
printf ("%s\n", candidates[i].name);
}
谢谢你的帮助!
为什么在fgets()之后有getchar()? 我认为这是你的罪魁祸首。
fgets()
getchar()
之后的getchar()
正在吃下一行的第一个字母。
读取名字的问题可能是由输入流中的杂散换行引起的。 要在输入循环之前刷新stdin
,您可以使用以下内容:
while((c = getchar()) != '\n' && c != EOF)
/* discard the character */;
我认为fflush(stdin)
是未定义的行为,所以不要这样做 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.