【发布时间】:2016-06-10 21:20:45
【问题描述】:
我只是在学习链表。我为自己编写了一个小程序来练习有关链表的机制。这是我第一次尝试做一个小的 pokedex(实际上没有保存任何东西)。所以我正在尝试正确设置输入。目前一切正常,没有错误,我可以执行它。
问题是第二次输入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++;
}
【问题讨论】:
-
在
scanf("%d",&firstPtr->number);之后写入getchar();(用于消耗换行符) -
我不太确定这是否真的有帮助,因为它会提示我输入一些内容,但问题仍然存在。我将在问题所在的主要帖子中进行编辑。
-
尝试使用
scanf("%d%*c", &firstPtr->number);而不是scanf("%d",&firstPtr->number); -
所有神奇宝贝的
POKEMON_LENGTH都固定了吗? -
好吧,我想引入一个字符串限制,因为我读了很多,出于安全原因这样做是好的。所以我将 POKEMON_LENGTH 定义为只有一些字符长(我认为可能是 15 个)