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

如何在C语言中仅用<stdio.h>删除文件非字母字符(禁用特定语法)

完善C代码实现删除冗余符号功能

需求说明

现有文件poem.txt内容如下:

*The ho$use cat sits.* 

*And sm%iles and) sing&s.*

*He% know*(s a l_ot* 

*Of s!ecret thi<ngs.*

要求删除其中的非必要符号(仅保留字母、空格、换行),写入新文件poem_modified.txt,且仅使用<stdio.h>库,不得使用数组、函数、结构体和指针。

原代码

#include <stdio.h>

int main() {
FILE *input;
FILE *output;

input  = fopen ("poem.txt", "r");
output = fopen ("poem_modified.txt", "w");

if (input == NULL || output == NULL)
{
    printf("Problem! \n");
    return 1;
}
char ch ;
while((ch=getc(input)) != EOF)

fprintf(output, "%c", ch);

fclose(input);
fclose(output); 
}

完善后的代码

#include <stdio.h>

int main() {
    FILE *input;
    FILE *output;

    input = fopen("poem.txt", "r");
    output = fopen("poem_modified.txt", "w");

    if (input == NULL || output == NULL)
    {
        printf("Problem! \n");
        return 1;
    }
    char ch;
    while((ch = getc(input)) != EOF)
    {
        // 仅保留大小写字母、空格和换行符
        if ((ch >= 'A' && ch <= 'Z') || 
            (ch >= 'a' && ch <= 'z') || 
            ch == ' ' || 
            ch == '\n')
        {
            fprintf(output, "%c", ch);
        }
    }

    fclose(input);
    fclose(output); 
    return 0;
}

代码说明

  • 新增字符判断逻辑:读取每个字符后,仅当字符为大小写字母、空格或换行符时才写入输出文件,其余冗余符号直接跳过。
  • 补全while循环的大括号,修正原代码语法问题(原代码无大括号会导致仅单条语句循环)。
  • 添加return 0;语句,符合C语言main函数的规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:05:24