我在C中使用sscanf和fscanf感到非常困难

时间:2018-11-27 02:33:39

标签: c

我正在尝试从文件中扫描字符串,但是fscanf()似乎只扫描两件事,我不明白为什么。

struct rider_profile array_assembler(FILE *fp){
    struct rider_profile new_profile;
    char buffer[150];
    int check;

    check = fscanf(fp, "%s \"%[^\"]\" %d %[A-Z] %[A-Z] %[0-9DNFOTL] %[0-9:]",
        new_profile.bike_race,
        new_profile.full_name,
        new_profile.rider_team,
        new_profile.rider_nationality,
        new_profile.placement_in_race,
        new_profile.race_time);

    printf("should be 7: %d", check);// it is only the first two that get scand.
    return new_profile;
}

我要扫描的字符串是:

ParisRoubaix "Greg VAN AVERMAET" | 32 BMC BEL | 1 5:41:07

1 个答案:

答案 0 :(得分:0)

不清楚确切地您希望分组如何进行,但是您必须考虑|

我不得不猜测如何对32 BMC BEL进行分组-可能有比我想出的更好的方法:

以下一些代码可以使您更加接近:

#include <stdio.h>

struct rider_profile {
    char bike_race[100];
    char full_name[100];
    char rider_team_number[100];
    char rider_team[100];
    char rider_nationality[100];
    char placement_in_race[100];
    char race_time[100];
};

struct rider_profile
array_assembler(FILE * fp)
{
    struct rider_profile new_profile;
    int check;

    check = fscanf(fp, "%100s \"%100[^\"]\" %*[|] %100[0-9] %100[A-Z] %100[A-Z] %*[|] %100[0-9DNFOTL] %100[0-9:]",
        new_profile.bike_race,
        new_profile.full_name,
        new_profile.rider_team_number,
        new_profile.rider_team,
        new_profile.rider_nationality,
        new_profile.placement_in_race,
        new_profile.race_time);

    printf("should be 7: %d\n", check); // it is only the first two that get scand.

    printf("test: bike_race='%s'\n",new_profile.bike_race);
    printf("test: full_name='%s'\n",new_profile.full_name);
    printf("test: rider_team_number='%s'\n",new_profile.rider_team_number);
    printf("test: rider_team='%s'\n",new_profile.rider_team);
    printf("test: rider_nationality='%s'\n",new_profile.rider_nationality);
    printf("test: placement_in_race='%s'\n",new_profile.placement_in_race);
    printf("test: race_time='%s'\n",new_profile.race_time);

    return new_profile;
}

int
main(int argc,char **argv)
{

    --argc;
    ++argv;

    FILE *fi = fopen(*argv,"r");
    array_assembler(fi);

    fclose(fi);

    return 0;
}

样本输入的输出为:

should be 9: 9
test: bike_race='ParisRoubaix'
test: full_name='Greg VAN AVERMAET'
test: rider_team_number='32'
test: rider_team='BMC'
test: rider_nationality='BEL'
test: placement_in_race='1'
test: race_time='5:41:07'

更新:

  

%s和%[]的宽度说明符,请

fscanf(fp, "%100s \"%100[^\"]\" %*[|] %100[0-9] %100[A-Z] %100[A-Z] %*[|] %100[0-9DNFOTL] %100[0-9:]"