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

C语言无内置函数实现my_split时输出异常问题求助

问题分析与解决方案

核心问题原因

首次输出为空的本质是第一次fgets读取到了仅含换行符的空行,再加上my_split函数的循环条件限制,导致没有任何内容写入strA和strB。具体触发点:

  1. scanf("%d%*c", &T)的%*c仅能读取一个字符,若输入缓冲区中存在多余字符(或部分环境下换行符处理异常),会导致后续fgets优先读取到残留的换行符。
  2. my_split的循环条件为while(*source != '\n'),若source仅含换行符,循环直接跳过,最终strA和strB被直接设为'\0',输出为空。

代码修复方案

1. 修复输入缓冲区处理(主函数)

替换原有的scanf语句,改用更可靠的方式清空输入缓冲区,确保fgets能正确读取目标行:

int main(void){
  int max_n = 200;
  char source[max_n];
  char strA[max_n];
  char strB[max_n];
  int T;
  scanf("%d", &T);
  // 彻底清空输入缓冲区,吃掉数字后的所有剩余字符(包括换行)
  while(getchar() != '\n');
  for(int i  = 0; i < T; i++){
    fgets (source, max_n, stdin);
    my_split(source, strA, strB, ';');
    printf("First: %s\n", strA);
    printf("Second: %s\n", strB);
  }
}

2. 修复my_split函数逻辑

  • 将循环条件改为while(*source != '\0'),确保处理到字符串结束(兼容无换行的最后一行)
  • 跳过换行符,避免将其写入结果字符串
  • 移除多余的指针解引用操作
void my_split(const char *source, char *first, char *second, const char delim){
    int ree = 1;
    while(*source != '\0'){
        // 跳过换行符,不写入结果
        if(*source == '\n'){
            source++;
            continue;
        }
        if(*source == delim){
            ree = 0;
            source++; // 仅移动指针,无需解引用
        }
        else{
            if(ree == 1){
                *first++ = *source++;
            }
            else {
                *second++ = *source++;
            }
        }
    }
    *first = '\0';
    *second = '\0';
}

修复后效果

运行修改后的代码,输入指定内容后会输出期望结果:

First: 2345.454
Second: 6737.98
First: this is the line
Second: splitted by semicolon

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:20:42