创建一个程序来提取(仅)文本文件中包含的字母字符,并将它们转储到不同的文件中。提取的字符必须是ASCII码为32到127的字符。
我无法解决这个问题,你能帮我吗?
#include <stdio.h>
int main()
{
FILE *fp1;
FILE *fp2;
char ch;
fp1 = fopen("bin.txt","r");
fp2 = fopen("text.txt","w");
ch = fgetc(fp1);
while(ch != EOF)
{
if(ch >= '32' && ch <= '127')
putc(ch,fp2);
else
continue;
}
fclose(fp1);
fclose(fp2);
return 0;
}
最佳答案
我在你的程序中发现了 3 个错误。首先,您只读取文件中的第一个字符。然后你没有正确检查它 - 请参阅注释掉并替换的行。第三种是当 fgetc
返回 int
时使用 char
类型,这可能是 EOF
。此外,当循环中没有更多语句时,不需要 continue
,并且您应该检查文件是否已打开。
#include <stdio.h>
int main()
{
FILE *fp1;
FILE *fp2;
int ch;
fp1 = fopen("bin.txt","r");
fp2 = fopen("text.txt","w");
if (fp1 == NULL || fp2 == NULL)
return 1; // bad files
while((ch = fgetc(fp1)) != EOF) // read a char in each loop
//if(ch >= '32' && ch <= '127') // don't test 'char' !
if(ch >= 32 && ch <= 127) // test as values
putc(ch,fp2);
fclose(fp1);
fclose(fp2);
return 0;
}
关于c - 使用 C 编程语言从文本文件中提取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29720772/