【问题标题】:Problem with the %[^,] thing while using scanf for stdin将 scanf 用于 stdin 时出现 %[^,] 问题
【发布时间】:2021-10-22 00:32:04
【问题描述】:
#include <stdio.h>
#include<string.h>

int main() {
    // Write C code here
    char word[20];
    char cat[20];
    printf("Enter the thing:");
    scanf("%[^,]",word);
    scanf("%[^,]",cat);
    printf("%s",word);
    printf("%s",cat);
    return 0;
}

这是我的代码,它打印出 word 的值,而不是 cat 的值?

【问题讨论】:

标签: c scanf


【解决方案1】:

%[^ 的工作方式是它一直扫描字符,直到找到其列表中的一个字符(在您的情况下,这只是 ,,但它实际上并没有吃掉那个字符并停留在那个点. 因此可视化问题,假设您在提示时输入Foo, bar, 作为输入,scanf("%[^,]",word); 将扫描Foo 并且文件位置将移动到, bar 的开头。调用scanf("%[^,]",cat); 时,,将立即被看到,并且不会扫描任何内容。

要解决此问题,您需要更改格式字符串以在之后吃掉,

scanf("%[^,],",word); // Notice the ',' after ']'
scanf(" %[^,],",cat); /* A leading ' ' will leave out any whitespace between `,` and
                         the next string */

运行固定程序示例:

Enter the thing:Foo, bar,
Foobar

【讨论】:

  • 并且cat 字符串的开头有一个空格,因为扫描集 (%[…]) 不会跳过前导空格。
  • @JonathanLeffler 我选择不添加,因为我不知道 OP 是否想要这种行为(与 Ted 不同,我保留第二个逗号的原因相同,尽管它看起来很奇怪)而且它与具体问题不完全相关。但我只会编辑以修正我的答案。
【解决方案2】:

第一次扫描后,, 留在输入流中。您需要在匹配模式中添加,[^,],

始终检查scanf 是否成功(在这些情况下,返回1)并始终将输入限制为缓冲区-1 中有空间的字符数,因此%19[^,], 在这两种情况下都是如此。如果第二次扫描不需要,,请跳过将其添加到模式匹配中。

结合两个扫描:

#include <stdio.h>
#include<string.h>

int main() {
    char word[20];
    char cat[20];
    printf("Enter the thing:");

    // in this version, "cat" doesn't need to be followed by a comma
    if(scanf("%19[^,],%19[^,]", word, cat) == 2) {
        printf(">%s<\n", word);
        printf(">%s<\n", cat);
    }
    return 0;
}

或者,可以将逗号添加到下一个scanf (",%19[^,]") 格式的开头,或者如果多个scanf 调用合并为一个,则区别会丢失。

【讨论】:

  • 或者,逗号可以添加到 next scanf 格式的开头,或者如果多个 scanf 调用合并为一。
  • @JohnBollinger 好点!我会将其复制到原样的答案中。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 2016-08-08
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
相关资源
最近更新 更多