【问题标题】:c - can't get multiple strings with scanf()c - 无法使用 scanf() 获取多个字符串
【发布时间】:2021-02-27 06:31:57
【问题描述】:

我一直在努力将两行用空格隔开,而我的 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:

【问题讨论】:

  • 你从未初始化过str1str2
  • 使它们成为数组而不是指针。 char str1[100], str2[100];
  • 好的,malloc 工作了,谢谢@Barmar

标签: c string scanf


【解决方案1】:

scanf(" %s", str1); 中的"%s" 期望str1 指向有效内存以存储字符串str1 未初始化 - 它未指向有效内存。

改为提供有效内存并限制输入宽度。

char str[100];
scanf("%99s", str1);

数组str在传递给scanf("%99s", str1);时转换为指向数组开头的指针

" %s" 中的前导空格不需要,因为"%s" 本身会占用前导空格,
就像" "

【讨论】:

    猜你喜欢
    • 2017-04-03
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多