在fscanf()中使用[]

Don*_*alo 6 c input scanf

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

"abc","def","ghi"
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

但是,以下失败:

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;
}
Run Code Online (Sandbox Code Playgroud)

我正在使用MSVC++ 08.我错过了什么?我在寻找与单一的解决方案fscanf()中的while循环.

pmg*_*pmg 7

有用???纯粹运气不好:-)

您的转换规格意味着

" %[\",]s "
         ^= optionally skip whitespace
        ^== read a literal 's'
  ^^^^^^=== read an unlimited string of quotes and commas
 ^========= optionally skip whitespace
Run Code Online (Sandbox Code Playgroud)

" %[a-zA-Z]s "
            ^= optionally skip whitespace
           ^== read a literal 's'
  ^^^^^^^^^=== read an unlimited string of letters
 ^============ optionally skip whitespace
Run Code Online (Sandbox Code Playgroud)

" %[\",]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
Run Code Online (Sandbox Code Playgroud)

我想你想要的

" %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
Run Code Online (Sandbox Code Playgroud)

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

if (scanf() == 3) /* expected 3 conversions */
{ /* ok */ }
else { /* oops, something went wrong */ }
Run Code Online (Sandbox Code Playgroud)