簡體   English   中英

fgets函數不會保存字符串中的第一個字母

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM