gpt4 book ai didi

c - 如何在C语言中查找文本文件中的字符串?

转载 作者:行者123 更新时间:2023-11-30 21:25:57 24 4
gpt4 key购买 nike

我需要读取文本文件中的字符串序列并从中提取信息。该文件包含游戏角色的名称和 ID。我需要为每个 HeroID 获取其各自的英雄名称(“url”标签),然后将其存储到链接列表中,但在处理文本文件时,我在 C 语法方面遇到了很多困难。具体来说,我不知道如何搜索 HeroID,获取相应的编号和 url 并将其存储到链接列表中。

这是我唯一能够编写的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct s_hero{
char name[30];
int id;
char attr[3];
struct s_hero* next;
} type_hero;

type_hero* initialize(void){
return NULL;
}

int main(){
type_hero* hero = initialize();
FILE *fp = fopen("npc_heroes.txt", "rt");

return 0;
}

这是我必须阅读的文本文件:http://notepad.cc/howtofindthestrings

最佳答案

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct s_hero {
char name[30];
int id;
char attr[3];
struct s_hero* next;
} type_hero;

type_hero* initialize(void){
return NULL;
}

char *strip_dq(char *str){
char *from, *to;

for(from = to = str; *from ; ++from){
if(*from != '"')
*to++ = *from;
}
*to = '\0';
return str;
}

type_hero *new_hero(char *name, int id){
type_hero *hero = calloc(1, sizeof(*hero));
strcpy(hero->name, name);
hero->id = id;
return hero;
}

void print_list(type_hero *top){
while(top){
printf("%d:%s\n", top->id, top->name);
top = top->next;
}
printf("\n");
}

void drop_list(type_hero *top){
if(top){
drop_list(top->next);
free(top);
}
}

int main(){
type_hero *hero = new_hero("", 0);//dummy
type_hero *curr = hero;
FILE *fp = fopen("npc_heroes.txt", "rt");
char buff[128];
while(1==fscanf(fp, "%127s", buff)){
if(strcmp(buff, "\"HeroID\"")==0){//label
fscanf(fp, "%s", buff);//data
int id = atoi(strip_dq(buff));
while(1==fscanf(fp, "%127s", buff) && strcmp(buff, "\"url\"")!=0)
;//skip
fscanf(fp, "%s", buff);//data
//char name[30];
//strcpy(name, strip_dq(buff));
curr = curr->next = new_hero(strip_dq(buff), id);
}
}
curr = hero;
hero = curr->next;
free(curr);//drop dummy

print_list(hero);
drop_list(hero);
return 0;
}

关于c - 如何在C语言中查找文本文件中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24848318/

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