我刚刚了解链接列表。我为自己写了一个小程序,练习关于链表的机制。这是我第一次尝试做一个小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