【问题标题】:I want to use EOF, but the result comes out as 1 when I input the integer [closed]我想使用EOF,但是当我输入整数时结果为1 [关闭]
【发布时间】:2021-10-22 03:48:15
【问题描述】:

为什么是结果 1?我不明白。 此代码是二叉搜索树的一部分。 我想制作一个程序来制作一个使用命令行获取输入节点的二叉搜索树。 所以,我使用了EOF,但这对我来说有点难。 我只是一个初学者。

int main() {
    struct node *root = NULL;
    int ch, te;
    int count = 0;
    while (1) {
        ch = scanf("%d", &te);
        printf("%d\n", ch);
        if (ch == EOF)
            break;
        else {
            insert(root, ch);
            count++;
        }
    }
    preorder(root);
    printf("%d", count);
    return 0;
}

【问题讨论】:

  • 请提供minimal reproducible example。我们没有struct nodeinsertpreorder 的定义(我们可能不需要它们,这个问题可能可以在没有不必要的树的情况下重现)。
  • 您希望scanf 何时返回EOF?你是如何做到这一点的?
  • 同样是 int main() { int ch, te;整数计数 = 0; while(1) { ch = scanf("%d", &te); printf("%d\n", ch);如果(ch== EOF)中断; } 返回 0; } 喜欢这段代码。我认为这是这段代码的问题
  • 我通过命令行输入ctrl+z来停止这个程序
  • scanf() 返回发生的成功转换的数量。在scanf("%d", &te); 中,您要求"%d"(即1-conversion)。所以在成功时,对scanf() 的调用的返回是1。如果您有 "%d %d",您将要求进行 2 次转换(到 int),成功后返回将是 2...参见 man 3 scanf

标签: c binary-search-tree


【解决方案1】:

您的代码中存在多个问题:

  • scanf() 返回成功转换的次数。在您的情况下,如果用户输入了数字,它可以返回 1,如果输入不是数字,则返回 0,如果流位于文件末尾,则返回 EOF。如果用户确实输入了一个数字并且scanf() 将转换后的数字存储到te 中,ch == 1 是预期的行为。与其与EOF 进行比较,不如测试ch != 1 是否能够捕获所有错误情况。

  • 您将返回值 ch 而不是 te 插入到树中。

  • insert(root, ch); 不能修改root,它最初设置为NULL,所以insert 执行的工作很可能丢失了。您没有发布insert 的代码,因此很难说如何正确解决此问题。

这是修改后的版本:

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

struct node *insert(struct node *root, int value) {
    // allocate a new node and insert it into the tree
    // modifying root to point to the new root node
    ...
    return root;
}

int main() {
    struct node *root = NULL;
    int te;
    int count = 0;
    while (scanf("%d", &te) == 1) {
        root = insert(root, ch);
        count++;
    }
    preorder(root);
    printf("%d\n", count);
    print_tree(root); // print the tree
    free_tree(root);  // free the tree
    return 0;
}

【讨论】:

    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 2017-09-30
    • 2021-11-03
    • 2020-11-04
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多