#include
#include
int main ()
{
char ch;
int m=0,n=0,p=0,count = 0;
FILE *fp = fopen("STRING.txt", "w+");
if (fp!=NULL)
{
printf("请输入要保存的字符串:\n");
ch = getchar();
while (ch!='\n') {
count++;
fputc(ch, fp);
ch = getchar();
}
printf("本次一共写入了%d个字符\n",count);
printf("\n");
rewind(fp);
ch = fgetc(fp);
while (ch!=EOF)
{
putchar(ch);
ch = fgetc(fp);
if (ch>='0'&&ch<='9')
m++;
else if (ch>='A'&&ch<='Z'||ch>='a'&&ch<='z')
n++;
else p++;
}
printf("\n");
printf("数字有%d个\n字母有%d个\n其他字符有%d个\n",m,n,p);
}
fclose(fp);
return 0;
}
以下引用自GPT的回答:
代码中统计字符数量的部分存在一些问题。具体来说,以下是需要注意的几点:
在统计字符数量时,你使用了fgetc()
函数从文件中逐个读取字符,并将字符存储在变量ch
中。然而,这个方法并不准确,因为在读取字符时,EOF
也会被读取进来,而且EOF
不会被计入任何类别中。这会导致统计结果不准确。
当统计数字、字母和其他字符数量时,你使用了不完整的条件判断。例如,你使用了ch>='0'&&ch<='9'
来判断数字字符,但没有考虑其他可能的字符。
为了解决这些问题,你可以采用以下改进的代码:
#include <stdio.h>
#include <ctype.h>
int main() {
char ch;
int digitCount = 0, letterCount = 0, otherCount = 0, totalCount = 0;
FILE *fp = fopen("STRING.txt", "w+");
if (fp != NULL) {
printf("请输入要保存的字符串:\n");
ch = getchar();
while (ch != '\n') {
fputc(ch, fp);
ch = getchar();
totalCount++;
}
printf("本次一共写入了%d个字符\n", totalCount);
printf("\n");
rewind(fp);
ch = fgetc(fp);
while (ch != EOF) {
putchar(ch);
totalCount++;
if (isdigit(ch)) {
digitCount++;
} else if (isalpha(ch)) {
letterCount++;
} else {
otherCount++;
}
ch = fgetc(fp);
}
printf("\n");
printf("数字有%d个\n字母有%d个\n其他字符有%d个\n", digitCount, letterCount, otherCount);
fclose(fp);
} else {
printf("无法打开文件。\n");
}
return 0;
}
在改进后的代码中,我引入了ctype.h
头文件,使用isdigit()
函数和isalpha()
函数来判断字符的类别。这样可以更准确地统计数字和字母的数量。此外,我还修正了统计总字符数量的错误,确保totalCount
能正确计数。最后,代码还增加了对文件打开失败的处理。
请注意,在使用文件指针操作文件之前,确保文件已经创建或存在,并具有适当的权限。另外,记得在程序结束前关闭文件,使用fclose()
函数。