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

C语言读取.txt文件中空行的问题求助

解决C语言读取奥赛罗对局文件中空行的问题

你的核心问题出在fscanf("%s\n", play)的使用上:%s格式符会自动跳过所有空白字符(包括换行、空格),所以文件里的空行直接被忽略,根本不会进入循环处理,自然没法记录代表跳过回合的"XX"。

改用fgets来读取整行内容就能解决这个问题,因为它会读取包括换行在内的整行数据,空行也能被捕获。下面是修改后的代码:

char line[100]; // 用足够大的缓冲区存整行,避免溢出
while (fgets(line, sizeof(line), file) != NULL) {
    // 先去掉行尾的换行符(如果存在)
    size_t len = strlen(line);
    if (len > 0 && line[len-1] == '\n') {
        line[len-1] = '\0';
        len--;
    }

    char play[3] = "XX"; // 默认设为XX,处理空行情况
    if (len == 2) { // 非空行,校验格式
        if ((line[0] >= 'A' && line[0] <= 'H') && (line[1] >= '1' && line[1] <= '8')) {
            strcpy(play, line);
        } else {
            // 格式错误,按原有逻辑处理
            fclose(file);
            free_datos(match);
            return 5;
        }
    } else if (len != 0) {
        // 既不是空行也不是合法的2字符落子位置,格式错误
        fclose(file);
        free_datos(match);
        return 5;
    }

    // 分配内存并存储play
    match->plays_counter++;
    match->plays = realloc(match->plays, match->plays_counter * sizeof(char *));
    match->plays[match->plays_counter - 1] = malloc(MAX_PLAY * sizeof(char));
    strcpy(match->plays[match->plays_counter - 1], play);
}

关键说明

  • fgets读取整行,包括空行(空行读取后是"\n",去掉换行符后就是空字符串)
  • 先处理换行符,避免后续判断字符串长度出错
  • 默认将play设为"XX",空行直接沿用这个值;非空行则校验格式,合法才覆盖play
  • 额外处理了长度既不是0也不是2的非法行,符合你的错误返回逻辑

另外注意你原有代码里的变量名错误:定义的是char play[3];,但判断条件里用了jugada,这会导致编译错误,上面的代码已经修正了这个问题。

内容的提问来源于stack exchange,提问作者Below Average C Programmer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:55:34