我试图读取用户输入的人名,名字的最后和最后用空格隔开,个人名字用换行符隔开。

例如:

乔治布什

巴拉克奥巴马

唐纳德·特朗普

到目前为止,这是我的代码:

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的返回值:


  成功分配的接收参数的数量(如果在分配第一个接收参数之前发生匹配失败,则为零);如果在分配第一个接收参数之前发生输入失败,则为EOF。


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


  EOF是类型为int且为负值的整数常量表达式。


因此,将while更改为:

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

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

10-11 19:37
查看更多