gpt4 book ai didi

C - strtok 有问题

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

我正在尝试将游戏的一些高分加载到这种结构中:

typedef struct{
char date_time[20];
int record_minutes;
int record_seconds;
int plays;
} Highscore;

高分存储在一个 txt 文件中,如下所示:“nrplays minutes seconds date_and_time”

例如15 2 10 31/12/2017-23:00:20

我用来读取文件的代码的第一位(只有 3 行,这就是我没有创建循环的原因)如下

void loadHighscores(){

FILE *f;

if (check_ifEmptyFile()==-3)
return;

f=fopen("highscores.txt", "r");

char linha[30];
char *token;

High1 = (Highscore *)malloc(sizeof(Highscore));

fgets(linha, 30, f);
printf("linha: %s", linha);

token = strtok(linha, " \n");
High1->plays=atoi(token);
printf("%d\n", High1->plays);

token = strtok(NULL, linha);
High1->record_minutes=atoi(token);
printf("%d\n", High1->record_minutes);

token = strtok(NULL, linha);
High1->record_seconds=atoi(token);
printf("%d\n", High1->record_seconds);

token = strtok(NULL, linha);
snprintf(High1->date_time, 20*sizeof(char), "%s",token);
printf("%s",High1->date_time);
}

输出是这样的

linha: 15 2 10 31/12/2017-23:00:20
15
2
0
/

这意味着 strtok 没有按照我的预期去做。有什么建议吗?

注意High1是之前定义的,malloc没有错,而且High1->date_time应该是整个31/12/2017-23:00:20 字符串。

最佳答案

strtok() 中,第二个参数应该是分隔符。因此,在您的情况下,应该是字符空间:' '。

token = strtok(linha, " ");

对于连续调用:

token = strtok(NULL, " ");

linha 中解析每一行的位置。

关于C - strtok 有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48039540/

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