C do…while循环双链表问题

C do…while循环双链表问题,c,C,为了练习,我实现了这个简单而无用的双链表。这是一份运动员名单和他们从事的运动。每个节点的定义如下: typedef struct node { char* name; char* sport; struct node* prev; struct node* next; }node; 我已经在main中创建了列表的第一个节点(node*head是全局定义的): 此do while循环旨在允许用户在终端向列表中添加他/她想要的任意多个节点: char names[50]; // declaring

为了练习,我实现了这个简单而无用的双链表。这是一份运动员名单和他们从事的运动。每个节点的定义如下:

typedef struct node {
char* name;
char* sport;
struct node* prev;
struct node* next;
}node;
我已经在main中创建了列表的第一个节点(node*head是全局定义的):

此do while循环旨在允许用户在终端向列表中添加他/她想要的任意多个节点:

char names[50]; // declaring the arrays wherein the names and sports will be stored temporarily
char sports[30];
char YorN; // this will store the result from the prompt
do {
    printf("name: ");
    fgets(names, 50, stdin);
    strtok(names, "\n"); // removing the "\n" that fgets adds so that name and     sport will be printed on the same line

    printf("sport: ");
    fgets(sports, 30, stdin);

    addNode(names, sports); // adds node to the head of the list
    printReverse(); // prints the list in reverse, giving the illusion that the user is adding to the tail

    printf("add a new name to the list? (Y or N): ");
    YorN = fgetc(stdin);
    YorN = toupper(YorN);
} while (YorN == 'Y');
对于第一个条目,它可以正常工作。输出:

name: Reggie Miller
sport: Basketball
Stephen Curry,Basketball
Reggie Miller,Basketball
add a new name to the list? (Y or N):
之后,如果用户选择“Y”添加新节点,终端将打印以下内容:

name: sport:
这只允许用户进入运动。然后输出以下内容:

name: sport: k
Stephen Curry,Basketball

,k


,k

add a new name to the list? (Y or N):
其中“k”是输入的运动项目。我认为addNode()或printReverse()函数没有问题,因此为了简洁起见,我省略了发布这些函数。然而,如果有人认为这些功能可能有问题,或者只是想看到它们,我很乐意发布它们。在我看来,这是循环的某个方面的问题,也许是我的fgets实现?当我尝试scanf时,它甚至第一次尝试都失败了。非常感谢您的帮助,谢谢

getc(stdin)
'\n'
放入
stdin
。因此,第二个循环
fgets
立即退出

您可以对
fgetc(stdin)执行虚拟调用在循环结束时

或者您可以
fgets
读取
“Y\n”
输入字符串

char answer[3];
fgets(answer, sizeof(answer), stdin);
YorN = toupper(answer[0]);

你能发布完整的代码而不是部分代码吗。这样很难理解。
fgetc(stdin)
'\n'
放入
stdin
。因此,第二个循环
fgets
立即退出。
fgets()
在第二次迭代中读取
Y
之后的换行符。为避免此类问题,不要在同一输入流上混合
fgetc
fgets
。坚持一个或另一个(在您的情况下,
fgets
可能是更好的选择)。
char answer[3];
fgets(answer, sizeof(answer), stdin);
YorN = toupper(answer[0]);