2016-07-07 66 views
2

所以我實現這個簡單而漂亮的無用雙鏈表只是爲了練習。它是一系列運動員和他們所玩的運動。每個節點的定義如下:做... while雙向鏈表的循環問題

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

我創建了一個主列表(節點*頭全局定義)的第一個節點:

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; 

該做的,而循環是爲了讓因爲他/她想要在終端的用戶添加儘可能多的節點列表:

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時,即使第一次嘗試失敗。任何幫助非常感謝,謝謝!

+0

你可以發佈整個代碼而不是部分嗎?它很難像這樣理解它。 – dazzieta

+7

'fgetc(stdin)'將'\ n''保存爲'stdin'。所以第二個循環'fgets'立即退出。 – LPs

+2

'fgets()'在第二次迭代中讀取'Y'後面的換行符。 – MikeCAT

回答

3

getc(stdin)'\n'stdin。所以第二個循環fgets立即退出。

您可以在循環結束時對fgetc(stdin);執行虛擬調用。

或者你fgets讀出"Y\n"輸入字符串。

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