如何在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
相关产品推荐
相关产品推荐

