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

为什么我的C语言程序写入文件时会额外输出一个换行?

问题原因

你的代码中对.的判断和后续的分隔符判断是两个独立的if分支,没有互斥逻辑:

  • 当读取到字符.时,第一个if分支会先输出一次换行,将循环终止标记repeat设为0
  • 由于.本身属于标点符号,会满足第二个if的ispunct(c)判定条件,会触发第二次换行输出,这就是多余换行的来源
  • 同时循环终止标记repeat = 0只会在下一次循环判断时生效,本次循环的剩余逻辑仍然会完整执行,无法阻断第二次换行的输出。

修复方案

在.的判断分支末尾加continue跳过本次循环的后续逻辑,或者将两个if改为互斥的if-else if结构即可,这里提供最简修改版本:

#include <stdio.h>
#include <ctype.h>
 
int main (){
    freopen("The Parsnip.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    int repeat = 1;
    int c = getchar();
    while (repeat)
    {
    
        if(c == '.')
        {
            putchar('\n');
            repeat = 0;
            continue; // 新增这行,跳过后续的分隔符判断逻辑
        }
        if (c == '\t'|| ispunct(c)|| c == ' ')
        {
            putchar('\n');
            c = getchar();
            while(c == '\n'||c == '\t'|| ispunct(c)|| c == ' ')
            {
                c = getchar();
            }
        }
        else
        {
         putchar(c);
         c = getchar();
        }
    }
   
    return 0;
}

如果不需要保留.作为终止符之前的最后一个换行,也可以直接删除if(c == '.')分支里的putchar('\n');,两种方式都可以解决多余换行的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:24:06