#include<stdio.h>
#include<stdlib.h>
FILE *fp1,*fp2;
char fname[30];
void openfile(void)
{ //函数1:打开用于输入和输出的文件
printf("输入要读的文件名");
gets(fname);
if((fp1=fopen(fname,"r"))==NULL)
{ printf("不能打开文件,按任意键退出");
getchar();exit(0);
}
printf("输入要写入的文件名");
gets(fname);
if((fp2=fopen(fname,"w"))==NULL)
{ printf("不能打开文件,按任意键退出");
getchar();exit(0);
}
}
void statis(void)
//函数2:统计字母、空格、数字及其他字符的个数
{ char ch;
int j;
long alpha,space,other,digit[10]={0};
alpha=space=other=0;
while((ch=fgetc(fp1))!=EOF)
if(ch>='A' && ch<='Z' || ch>='a' && ch<='z')
alpha++;
else if(ch==' '||'\t'||'\n')
space++;
else if(ch>='0'&&ch<='9')
digit[ch-'0']++;
else
other++;
fclose(fp1);
fprintf(fp2,"alpha:%d space:%d other:%d\n",alpha,space,other);
for(j=0;j<=9;j++)
printf(fp2,"%d:%d \n",j,digit[j]);
close(fp2);
}
main()
{
openfile();
statis();
}
统计一个文本文件中的字符、空格、数字、和其他符号个数,把结果输出到一个文件里。程序开始先输入要统计的文件名,再输入要建立并保存结果的文件名。
问题:程序不统计数字和其他字符,都统计到空格、换行里去了。
#include<stdlib.h>
FILE *fp1,*fp2;
char fname[30];
void openfile(void)
{ //函数1:打开用于输入和输出的文件
printf("输入要读的文件名");
gets(fname);
if((fp1=fopen(fname,"r"))==NULL)
{ printf("不能打开文件,按任意键退出");
getchar();exit(0);
}
printf("输入要写入的文件名");
gets(fname);
if((fp2=fopen(fname,"w"))==NULL)
{ printf("不能打开文件,按任意键退出");
getchar();exit(0);
}
}
void statis(void)
//函数2:统计字母、空格、数字及其他字符的个数
{ char ch;
int j;
long alpha,space,other,digit[10]={0};
alpha=space=other=0;
while((ch=fgetc(fp1))!=EOF)
if(ch>='A' && ch<='Z' || ch>='a' && ch<='z')
alpha++;
else if(ch==' '||'\t'||'\n')
space++;
else if(ch>='0'&&ch<='9')
digit[ch-'0']++;
else
other++;
fclose(fp1);
fprintf(fp2,"alpha:%d space:%d other:%d\n",alpha,space,other);
for(j=0;j<=9;j++)
printf(fp2,"%d:%d \n",j,digit[j]);
close(fp2);
}
main()
{
openfile();
statis();
}
统计一个文本文件中的字符、空格、数字、和其他符号个数,把结果输出到一个文件里。程序开始先输入要统计的文件名,再输入要建立并保存结果的文件名。
问题:程序不统计数字和其他字符,都统计到空格、换行里去了。