2015-05-07 45 views
1

我是C新手,我試圖學習鏈表,但出於某種原因,我不能給出多個值。程序在給出一個值後結束。 這裏是我的代碼:爲什麼我無法在鏈接列表中輸入多個條目?

#include<stdio.h> 
#include<stdlib.h> 
typedef struct node_type { 
    int data; 
    struct node_type *next; 
} node; 

int main() 
{ 
    typedef node *list; 
    list head, temp; 
    char ch; 
    int n; 
    head = NULL; 
    printf("enter Data?(y/n)\n"); 
    scanf("%c", &ch); 

    while (ch == 'y' || ch == 'Y') 
    { 
     printf("\nenter data:"); 
     scanf("%d", &n); 
     temp = (list)malloc(sizeof(node)); 
     temp->data = n; 
     temp->next = head; 
     head = temp; 
     printf("enter more data?(y/n)\n"); 

     scanf("%c", &ch); 

    } 
    temp = head; 
    while (temp != NULL) 
    { 
     printf("%d", temp->data); 
     temp = temp->next; 
    } 

    return 0; 
} 

回答

1

改變這樣的:scanf("%c", &ch);這個scanf(" %c", &ch);

你的代碼沒有采取任何輸入是因爲scanf函數消耗從緩衝區換行的原因。在讀取字符之前,%c之前的空格會導致scanf()在緩衝區中跳過空格和換行符。

Working code

+0

謝謝。它現在可以工作:D – joker

相關問題