在fscanf()中使用[]

我有一个包含以下内容的文本文件
"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",]s%[a-zA-Z]s ",garbage,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+⬑ * 默认成员函数 原来C++类中,有6个默认成员函数: 构造函数 析构函数 拷贝...
#pragma once // 1. 设计一个不能被拷贝的类/* 解析:拷贝只会放生在两个场景中:拷贝构造函数以及赋值运...
C类型转换 C语言:显式和隐式类型转换 隐式类型转化:编译器在编译阶段自动进行,能转就转,不能转就编译...
//异常的概念/*抛出异常后必须要捕获,否则终止程序(到最外层后会交给main管理,main的行为就是终止) try...
#pragma once /*Smart pointer 智能指针;灵巧指针 智能指针三大件//1.RAII//2.像指针一样使用//3.拷贝问...
目录<future>future模板类成员函数:promise类promise的使用例程:packaged_task模板类例程...