2016-08-28 7 views
0

Cで単純なリンクリストを作成しようとしていますが、プログラムでは「ノードの数を増やしますか?」の部分はスキップします。 ここに私のプログラムがあります:リンクリストの要素を入力中の反復

#include<stdio.h> 
#include<stdlib.h> 

struct node{ 
    int data; 
    struct node *next; 
}*start = NULL; 

void createlist() 
{ 
    int item; 
    char choice = 'y'; 

    struct node *newNode; 
    struct node *current; 

    while(choice != 'n') 
    { 
     printf("Enter item to add in the Linked List\n\n"); 
     scanf("%d", &item); 

     newNode = (struct node *)malloc(sizeof(struct node)); 

     newNode->data = item; 
     newNode->next = NULL; 

     if(start == NULL) 
     { 
      start = newNode; 
      current = newNode; 
     } 
     else 
     { 
      current->next = newNode; 
      current = newNode; 
     } 

     printf("Enter more nodes?[y/n]\n"); 
     scanf("%c", &choice); 
    } 
} 

void display() 
{ 
    struct node *new_node; 
    printf("Your node is :\n"); 
    new_node = start; 
    while(new_node!=NULL) 
    { 
     printf("%d ---> ", new_node->data); 
     new_node = new_node->next; 

    } 
} 

int main() 
{ 
    createlist(); 
    display(); 
    return 0; 
} 

出力: Program skipping choice input part

しかし、私は文字からint型選択肢 varaiableを変更すると、プログラムが完全に実行されます。ここ は、作業機能があります:選択文字型である場合、プログラムが正しく動作しない理由を

void createlist() 
{ 
    int item; 
    int choice = 1; 

    struct node *newNode; 
    struct node *current; 

    while(choice != 0) 
    { 
     printf("Enter item to add in the Linked List\n\n"); 
     scanf("%d", &item); 

     newNode = (struct node *)malloc(sizeof(struct node)); 

     newNode->data = item; 
     newNode->next = NULL; 

     if(start == NULL) 
     { 
      start = newNode; 
      current = newNode; 
     } 
     else 
     { 
      current->next = newNode; 
      current = newNode; 
     } 

     printf("Enter more nodes?\n[NO - 0, YES - 1]\n"); 
     scanf("%d", &choice); 
    } 
} 

君たちは私を教えていただけますか?

+0

私の経験では、 'newline'と' space'は 'scanf'と混在しているときには実際には' char'であり、 'integer'はまったく異なるデータ型です。それがあなたがそのような行動を観察した理由です。それほど心配しないでください。安全にプレイし、%dを使用してください... :) –

+0

おかげで!今正しく動作します。 :-) –

+0

'scanf("%s "、&choice);を使うと動作します。 。 。 – Afshin

答えて

1

入力バッファに%cフォーマットのために読み込まれているnewlineが残っています。

scanf("%c", &choice); 

scanf(" %c", &choice);` 

に先頭にスペースが最初に空白をきれいに scanfを伝え変更します。これは %d形式で自動的に発生します。

+0

助けてくれてありがとう! –

関連する問題