You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中如何从宝可梦属性字符串提取整数用于战斗函数?

从宝可梦属性字符串提取整数的实现方案

针对你用fgets读取的宝可梦属性行(比如1 Pikachu fire 10 6 30),这里提供两种C语言下的整数提取方案,直接适配后续战斗函数的调用需求:

方法一:用sscanf直接解析(最简洁)

sscanf可以按照固定格式直接从字符串中提取对应类型的数据,完美匹配你每行的属性结构:

步骤1:定义宝可梦结构体(方便传递给战斗函数)

typedef struct {
    int id;
    char name[20];
    char element[20];
    int atk;
    int defense;
    int hp;
} Pokemon;

步骤2:读取并解析行数据

char line_buffer[100];
Pokemon current_pokemon;
FILE *fp = fopen("Pokemons.txt", "r");

if (fp == NULL) {
    // 处理文件打开失败的情况
    return 1;
}

// 逐行读取文件
while (fgets(line_buffer, sizeof(line_buffer), fp) != NULL) {
    // 按格式提取数据:整数id → 字符串name → 字符串element → 三个整数属性
    sscanf(line_buffer, "%d %s %s %d %d %d", 
           &current_pokemon.id, 
           current_pokemon.name, 
           current_pokemon.element, 
           &current_pokemon.atk, 
           &current_pokemon.defense, 
           &current_pokemon.hp);
    
    // 将解析后的宝可梦传入战斗函数
    // battle(&current_pokemon, opponent_pokemon);
}

fclose(fp);

sscanf的格式字符串%d %s %s %d %d %d完全对应每行的字段顺序,直接把变量地址传入即可完成提取,无需额外处理分割逻辑。

方法二:用strtok分割+atoi转换(更灵活)

如果需要对字段做更复杂的预处理,可以先用strtok按空格分割字符串,再用atoi将数字字符串转为整数:

char line_buffer[100];
char *token;
Pokemon current_pokemon;
FILE *fp = fopen("Pokemons.txt", "r");

if (fp == NULL) {
    return 1;
}

while (fgets(line_buffer, sizeof(line_buffer), fp) != NULL) {
    // 移除fgets读入的换行符,避免干扰分割
    line_buffer[strcspn(line_buffer, "\n")] = '\0';
    
    // 分割第一个字段:id
    token = strtok(line_buffer, " ");
    current_pokemon.id = atoi(token);
    
    // 分割第二个字段:name
    token = strtok(NULL, " ");
    strcpy(current_pokemon.name, token);
    
    // 分割第三个字段:element
    token = strtok(NULL, " ");
    strcpy(current_pokemon.element, token);
    
    // 分割第四个字段:atk
    token = strtok(NULL, " ");
    current_pokemon.atk = atoi(token);
    
    // 分割第五个字段:defense
    token = strtok(NULL, " ");
    current_pokemon.defense = atoi(token);
    
    // 分割第六个字段:hp
    token = strtok(NULL, " ");
    current_pokemon.hp = atoi(token);
    
    // 传入战斗函数
    // battle(&current_pokemon, opponent_pokemon);
}

fclose(fp);

这种方式适合字段格式可能有变化的场景,比如字段间有多个空格的情况,strtok会自动忽略连续的分隔符。

内容的提问来源于stack exchange,提问作者Matheus Ferrer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 23:45:08