我正在尝试读取用户输入的人名,名字和姓氏用空格分隔,个人姓名用换行符分隔。
例如:
乔治·布什
巴拉克·奥巴马
唐纳德·特朗普
这是我迄今为止的代码:
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) 时,它可以工作,但是我无法存储名字和姓氏,因为它们由空格分隔。
最佳答案
引用评论中指出的内容,
来自here的scanf
的返回值:
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/