gpt4 book ai didi

c - 我在 C 中很难使用 sscanf 和 fscanf

转载 作者:太空宇宙 更新时间:2023-11-04 04:14:28 24 4
gpt4 key购买 nike

我正在尝试从文件中扫描一个字符串,但似乎 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

最佳答案

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

我不得不猜测如何对 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'

更新:

Width specifiers for %s and %[], please

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

关于c - 我在 C 中很难使用 sscanf 和 fscanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53491928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com