c - 在 fscanf() 中使用 []

标签 c input scanf

我有一个包含以下内容的文本文件:

"abc","def","ghi"

以下工作可以正确读取文件内容:

int main()
{
    char name[1024] = {0};
    FILE *file = fopen("file.txt", "r");

    while(1)
    {
        if (fscanf(file, " %[\",]s ", name) == EOF)
            break;
        if (fscanf(file, " %[a-zA-Z]s ", name) == EOF)
            break;

        printf("%s\n", name);
    }

    return 0;
}

但是,以下操作失败了:

int main()
{
    char name[1024] = {0}, garbage[5];
    FILE *file = fopen("file.txt", "r");

    while(1)
    {
        if (fscanf(file, " %[\",]s%[a-zA-Z]s ", garbage, name) == EOF)
            break;

        printf("%s\n", name);
    }

    return 0;
}

我正在使用 MSVC++ 08。我缺少什么?我正在寻找在 while 循环中使用单个 fscanf() 的解决方案。

最佳答案

有用吗???纯粹的倒霉:-)

您的转换规范意味着

" %[\",]s "
         ^= optionally skip whitespace
        ^== read a literal 's'
  ^^^^^^=== read an unlimited string of quotes and commas
 ^========= optionally skip whitespace

" %[a-zA-Z]s "
            ^= optionally skip whitespace
           ^== read a literal 's'
  ^^^^^^^^^=== read an unlimited string of letters
 ^============ optionally skip whitespace

" %[\",]s%[a-zA-Z]s "
                   ^= optionally skip whitespace
                  ^== read a literal 's'
         ^^^^^^^^^=== read an unlimited string of letters
        ^============ read a literal 's'
  ^^^^^^============= read an unlimited string of quotes and commas
 ^=================== optionally skip whitespace

我觉得你想要

" %4[\",]%1023[a-zA-Z] "
                      ^= optionally skip whitespace
         ^^^^^^^^^^^^^== read a string of at most 1023 letters
  ^^^^^^^=============== read a string of at most 4 quotes and commas
 ^====================== optionally skip whitespace

除此之外,scanf 返回成功转换的次数或出错时返回 EOF。当您应该与 1(或 2,或其他)进行比较时,您正在将结果值与 EOF 进行比较:与您期望的转化次数进行比较。

if (scanf() == 3) /* expected 3 conversions */
{ /* ok */ }
else { /* oops, something went wrong */ }

关于c - 在 fscanf() 中使用 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3981958/

相关文章:

c - 使用环境变量的缓冲区溢出

c - 嵌套的结构值在没有任何函数作用于它们的情况下发生变化。帮我理解为什么

c++ - 键盘 Hook 问题

c - 为什么 getchar 不停止获取输入?

c - 如何在 C 中使用 EOF 标准输入

c - Valgrind block 丢失,从哪里释放?

c++ - 反转字符串: Why is this crashing?

r - 使用直方图作为 R 中的输入

java - Java 循环中的用户输入和求和问题

c++ - 如何使用 fseek() 进入一行的开头