无法找到这个简单的C代码有什么问题

时间:2015-01-02 18:11:27

标签: c binary-search-tree scanf gcc-warning

它是一个简单的树插入和遍历代码。

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

struct tree
{
    struct tree *left;
    struct tree *right;
    int value;
};

typedef struct tree node;

void insertNode(node **root, int val)
{
    node *temp = NULL;
    if(!(*root))
    {
        temp = (node*) malloc(sizeof(node));
        temp->value = val;
        temp->left = NULL;
        temp->right = NULL;
        *root = temp;
    }

    if(val < (*root)->value)
        insertNode(&(*root)->left, val);

    if(val >= (*root)->value)
        insertNode(&(*root)->right, val);
}

void preOrder(node *root)
{
    if(root)
    {   printf(" %d",root->value);
        preOrder(root->left);
        preOrder(root->right);
    }
}

void inOrder(node *root)
{
    if(root)
    {
        inOrder(root->left);
        printf(" %d",root->value);
        inOrder(root->right);
    }
}

void postOrder(node *root)
{
    if(root)
    {
        postOrder(root->left);
        postOrder(root->right);
        printf(" %d",root->value);
    }
}

void delTree(node *root)
{
    if(root)
    {
        delTree(root->left);
        delTree(root->right);
        free(root);
    }
}

int main()
{
    int val;
    char ch; ch = 'y';
    node *root;

    while(ch == 'y')
    {
        scanf("Enter the node value: %d", &val);
        insertNode(&root, val);
        scanf("Want to enter more: %c", &ch);
    }

    printf("\nInOrder traversal:\n");
    inOrder(root);
    printf("\nPreOrder traversal:\n");
    preOrder(root);
    printf("\nPostOrder traversal:\n");
    postOrder(root);

    delTree(root);
    printf("Tree Deleted.");

    return 0;
}

代码似乎没有问题,并且没有显示任何错误。虽然编译时会显示警告;

ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute

似乎是因为忽略了scanf的返回值而启动的,来自ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]?

但即使在抑制警告和编译可执行文件时也没有任何输入。这是为什么。我在CodeBlocks IDE上运行代码。

ideone上的情况相同,http://ideone.com/jOnjEK

感谢任何帮助或建议。

1 个答案:

答案 0 :(得分:1)

scanf("Enter the node value: %d", &val);应该是

scanf("%d", &val);

scanf("Want to enter more: %c", &ch);应该是

scanf(" %c", &ch);

假设你打算这个

printf("Enter the node value:\n");
if(scanf("%d", &val) != 1)
{
printf("Integer not read \n");
break;
} 

printf("Want to enter more:\n");
if(scanf(" %c", &ch) != 1)
{
printf("character not read\n");
break;
}

记下%c

scanf()之前的空格