C 编程 - 将空格分隔的字符串读入 BST

标签 c scanf binary-search-tree

我正在尝试读取用户输入的人名,名字和姓氏用空格分隔,个人姓名用换行符分隔。

例如:

乔治·布什

巴拉克·奥巴马

唐纳德·特朗普

这是我迄今为止的代码:

int main(int argc, char** argv) {
  char string[20+1];
  struct bst* tree = NULL;
  printf("Enter some strings: \n");

  while (scanf("%[^\n]%*c",string)) {
     tree=insert(tree,string);
  } 
}

我的插入函数是:

struct bst*
insert(struct bst* tree, char input[]) {
    struct bst* newnode;
    newnode = (struct bst*)malloc(sizeof(*newnode));

    strcpy(newnode->data, input);
    newnode->left = newnode->right = NULL;

    if (tree == NULL) {
        return newnode;
    } 

    if (strcmp(input,tree->data)<0) {
        tree->left=insert(tree->left,input);
    } else {
        tree->right=insert(tree->right,input);
    }
    return tree;
  }

问题是对用户输入的扫描是没有止境的。 当我将 scanf 更改为 scanf("%s",string) 时,它可以工作,但是我无法存储名字和姓氏,因为它们由空格分隔。

最佳答案

引用评论中指出的内容,

来自herescanf的返回值:

Number of receiving arguments successfully assigned (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or EOF if input failure occurs before the first receiving argument was assigned.

需要更改 while 中的条件,因为:

EOF is a integer constant expression of type int and negative value.

因此将 while 更改为:

while (scanf("%[^\n]%*c",string) == 1)

关于C 编程 - 将空格分隔的字符串读入 BST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51904798/

相关文章:

c - 指针声明数组

C - 尝试确定由 getline() 填充的缓冲区中的元素数

c - scanf 之后 fgets 不起作用

python - 二叉搜索树,逻辑和语法错误

javascript - Javascript中如何使用递归函数遍历树

c - 请求对原始 crc32 校验和的评论

c - 双指针取消引用时的内核错误

C程序使用scanf进入无限循环

c - 带有 %n 的 scanf 给出了错误的输出

c - 二叉搜索树查找输出