【问题标题】:do...while loop issue with doubly linked list [duplicate]do ...while循环问题与双向链表[重复]
【发布时间】:2016-07-07 14:48:35
【问题描述】:

所以我实现了这个简单且毫无用处的双向链表只是为了练习。这是运动员和他们从事的运动的列表。每个节点定义如下:

typedef struct node {
char* name;
char* sport;
struct node* prev;
struct node* next;
}node;

我在 main 中创建了列表的第一个节点(node* head 是全局定义的):

head = malloc(sizeof(node));
if (head == NULL) {
    printf("malloc failed");
    return 1;
}
head->name = "Stephen Curry";
head->sport = "Basketball";
head->next = NULL;
head->prev = NULL;

这个 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 时,即使是第一次尝试也失败了。非常感谢任何帮助,谢谢!

【问题讨论】:

  • 您能否发布整个代码而不是其中的一部分。像这样很难理解。
  • fgetc(stdin) 离开 '\n'stdin。所以第二个循环fgets 立即退出。
  • fgets() 在第二次迭代中正在读取Y 之后的换行符。
  • 为避免此类问题,请勿在同一输入流上混合fgetcfgets。始终坚持其中一个(在您的情况下,fgets 可能是更好的选择)。

标签: c


【解决方案1】:

getc(stdin) 离开 '\n'stdin。所以第二个循环fgets 立即退出。

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

或者你fgets读出"Y\n"输入字符串。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多