Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C fgets函数不保存字符串中的第一个字母_C - Fatal编程技术网

C fgets函数不保存字符串中的第一个字母

C fgets函数不保存字符串中的第一个字母,c,C,我写了一个程序,从用户那里得到一个数字,然后从用户那里得到每个数字的名称。。。 例如,如果用户输入数字10,它将使用10个名称并将其放入结构数组中。。。 一切都很好,除了当我打印名字时,它跳过了第一个字母。。。 比如说,如果我写上“Amit”这个名字,它会写上“mit”,而且,我输入的最后一个字符串根本没有保存。。 以下是我写的: const number_candidates; // Getting the number of candidates #define MAX 256 #defin

我写了一个程序,从用户那里得到一个数字,然后从用户那里得到每个数字的名称。。。 例如,如果用户输入数字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();
 }
}
const number_候选者;//获取候选人数量
#定义最大值256
#定义最小候选10
#定义最大候选值60000
typedef struct candidate//获取每个候选对象的详细信息
{
字符名[MAX];
int sing_等级;
每级整数;
int cam_级;
沙曼提乌级国际学校;
}候选人;
void get\u details\u候选者(候选者[MAX])
{
int i=0;
printf(“\n”);
对于(i=0;i
这是印刷品:

    for (i = 0 ; i < number_candidates ; i++)     
{
    printf ("%s\n", candidates[i].name);
}
for(i=0;i
谢谢你的帮助

为什么在fgets()之后有getchar()?我认为那是你的罪魁祸首。

fgets()之后的
getchar()
正在吃掉下面一行的第一个字母

您读取名字的问题可能是由输入流中的错误换行引起的。要在输入循环之前刷新stdin,可以使用以下方法:

while((c = getchar()) != '\n' && c != EOF)
/* discard the character */;

我认为
fflush(stdin)
是未定义的行为,所以不要这样做

为什么在
fgets()之后有
getchar()
?因为在循环第一次启动时,它没有名字……这很奇怪。我不知道为什么你的第一个字符串没有被读取,但是
getchar()
调用肯定在消耗下面输入行的第一个字符。你是对的。。。所以现在我唯一的问题是第一个fgets…当我取下getchar()时;从fgets来看,它工作正常,每个名字都有第10个单词和第一个字母,但在第一次要求名字时,它没有从用户那里得到名字,而是直接要求第二个名字。。。。