c - 无法使用 scanf() 获取多个字符串
c - can't get multiple strings with scanf()
我一直在努力用 space 分隔两行,我的 scanf() 无法正常工作
这是代码
char *str1, *str2;
while(1) {
printf("Enter string:\n");
scanf(" %s", str1);
printf("Then;");
scanf(" %s", str2);
if(strcmp(str1, "exit") == 0){break;}
printf("Output:\n %s %s\n", str1, str2);
}
但是我的输出是这样的:
Enter string:
ok
Then;hello
Output:
ok (null)
Enter string:
Then;
什么会导致这个问题?并在循环第二次时打印第一个输出。
Enter string:
ok
Then;hello
Output:
ok (null)
Enter string:
Then;well
Output:
hello (null)
Enter string:
Then;no
Output:
well (null)
Enter string:
scanf(" %s", str1);
中的 "%s"
期望 str1
指向有效内存以存储 字符串 。 str1
未初始化 - 它未指向有效内存。
改为提供有效内存并限制输入宽度。
char str[100];
scanf("%99s", str1);
数组str
在传递给scanf("%99s", str1);
时转换为指向数组开头的指针
不需要 " %s"
中的前导 space,因为 "%s"
本身会消耗前导白色-space,
就像 " "
.
我一直在努力用 space 分隔两行,我的 scanf() 无法正常工作 这是代码
char *str1, *str2;
while(1) {
printf("Enter string:\n");
scanf(" %s", str1);
printf("Then;");
scanf(" %s", str2);
if(strcmp(str1, "exit") == 0){break;}
printf("Output:\n %s %s\n", str1, str2);
}
但是我的输出是这样的:
Enter string:
ok
Then;hello
Output:
ok (null)
Enter string:
Then;
什么会导致这个问题?并在循环第二次时打印第一个输出。
Enter string:
ok
Then;hello
Output:
ok (null)
Enter string:
Then;well
Output:
hello (null)
Enter string:
Then;no
Output:
well (null)
Enter string:
scanf(" %s", str1);
中的 "%s"
期望 str1
指向有效内存以存储 字符串 。 str1
未初始化 - 它未指向有效内存。
改为提供有效内存并限制输入宽度。
char str[100];
scanf("%99s", str1);
数组str
在传递给scanf("%99s", str1);
不需要 " %s"
中的前导 space,因为 "%s"
本身会消耗前导白色-space,
就像 " "
.