-1

Cで双方向リンクリストを使用してツリーを作成しています。その関数で再帰呼び出しを使用していますが、どういうわけか機能しません。私のコードは:

struct node
{
    int data;
    struct node *right;
    struct node *left;
};

struct node* getNode()
{
    struct node *temp;
    temp= (struct node *)malloc(sizeof(struct node));
    temp->right=NULL;
    temp->left=NULL;
    return temp; 
}

ここでは、以下の関数で問題が発生しています。

struct node* maketree()
{
    struct node *t;
    t=getNode(); 
    int value;
    char choice1='n',choice2='n';
    printf("\nenter the value to the node");
    scanf("%d",&value);
    t->data=value;
    printf("\nis there any left child??\n");
    scanf("%c",&choice1);               // I think here my problem is .
    if (choice1 == 'y')
    {
        t->left=maketree();   
    }

    printf("\nis there any right child??\n");
    scanf("%c",&choice2);
    if (choice2 == 'y' || choice2 == 'Y')
    {
        t->right=maketree();   

    }
    return t;
}

int main (void)
{
    struct node *t;
    t=maketree();
    return;
}

コードは適切にコンパイルされますが、問題は、コードが私の選択を待たないことです (私は を使用scanf()します。C は端末に入力を入力するまで待機する必要があります)。出力は次のとおりです。

enter the value to the node4

is there any left child??

is there any right child??

手伝ってください。

4

3 に答える 3

0

問題は、\r2 番目の scanf に送信され、最初の scanf から残っていることです。

また、scanfで1文字しか読み取っていないため(これはお勧めしません-getchar()代わりに使用してください)、キャリッジリターン( )を受け入れます\r。それでも 2 番目の scanf を使用したい場合はfflush(stdin)、最初の scanf() の直後に標準入力をフラッシュします。

于 2013-08-22T06:38:22.307 に答える