我剛剛瞭解鏈接列表。我爲自己寫了一個小程序,練習關於鏈表的機制。這是我第一次嘗試做一個小pokedex(實際上沒有保存任何東西)。所以我正在嘗試正確設置輸入。目前一切正常,沒有錯誤,我可以執行它。鏈接列表中的字符串輸入[C]
問題是第二次輸入的pokemon名稱不能在任何數據中讀取,而是跳過讀入並直接進入scanf函數,爲什麼會出現這種情況?
void addPokemon(void){
pokemonPtr firstPtr;
pokemonPtr thisPokemon;
firstPtr = NULL;
firstPtr =(pokemon *) malloc(sizeof(pokemon));
firstPtr->name = malloc(sizeof(char) * POKEMON_LENGTH);
printf ("Enter the name of the Pokemon.\n");
fgets(firstPtr->name, POKEMON_LENGTH, stdin);
的問題就在這裏,這FGETS是不是真的被執行,所以基本上不會提示用戶輸入的字符串。
printf ("Enter the number of the Pokemon.\n");
scanf("%d",&firstPtr->number);
firstPtr->next =(pokemon *) malloc(sizeof(pokemon));
thisPokemon = firstPtr->next;
int i = 0;
while (i < 10){
thisPokemon->name = malloc(sizeof(char) * POKEMON_LENGTH);
printf ("Enter the name of the Pokemon.\n");
fgets(thisPokemon->name, POKEMON_LENGTH, stdin);
printf ("Enter the number of the Pokemon.\n");
scanf("%d",&thisPokemon->number);
thisPokemon->next =(pokemon *) malloc (sizeof(pokemon));
thisPokemon = thisPokemon->next;
i++;
}
寫入任何其他空白空間(
'\0'
,'\t'
或' '
)'的getchar();'(對於消耗換行)後'scanf(「%d」,&firstPtr-> number);' – BLUEPIXY我不太確定這是否真的有幫助,因爲它會提示我輸入內容,但問題仍然存在。 我將在主要帖子中正確編輯問題。 –
嘗試'scanf(「%d%* c」,&firstPtr-> number);'而不是'scanf(「%d」,&firstPtr-> number);' – BLUEPIXY