统计文件中的字符和符号数量程序设计
一 初级要求
- 需要用到文件操作及相关函数,对磁盘中的文件进行读写,其用法类似于屏幕输入输出。
- 统计和输出其中包含空格数量,数字及符号的数量,英文字符数量,英文单词数量(规定单词间以一个或多个空格分开)。
二 高级要求 - 统计段落数。
- 能够分别统计出中文字符和英文字符个数。
- 统计信息输出到文件结尾。
主函数
int main()
{
int i = 0;
char str[MAX_LINE] = "";
char s[MAX_LINE] = "";
int chinese,word;
FILE *read;//文件指针
FILE *write=fopen("hao.txt", "a");
char c;
read = fopen("hao.txt", "r");//以只读方式打开
c = fgetc(read);
while (c != EOF||i<strlen(str))
{
str[i] = c;
c = fgetc(read);
i++;
}
puts(str);
count_1();
chinese=count_zw(str);//统计单词个数
word=count_word(str);//统计中文字符个数
sprintf(s, "汉 字:%d个\n单 词:%d\n个",chinese,word);
fputs(s, write); //写入文件
fclose(write);
fclose(read);
system("pause");
return 0;
}
初级要求
void count_1()//任务要求一
{
// int n;
int l = 0, m = 0, j = 0, p = 0,para = 1;//l:英文字母数;m:空格数;j:数字个数;p:符号个数
char s[MAX_LINE] = "";
FILE *w=fopen("hao.txt","r");
FILE *write=fopen("hao.txt", "a");
int ch;
while ((ch=fgetc(w))!=EOF)
{
if (ch == ' ')
m++;
else if (ch >= '0'&&ch <= '9')
j++;
else if ((ch <= 'z'&&ch >= 'a') || (ch >= 'A'&&ch <= 'Z'))
l++;
else if((ch>=33&&ch<=47)||(ch>=58&&ch<=64)||(ch>=91&&ch<=96)||(ch>=123&&ch<=126))
p++;
else if(ch==10||ch==27||ch==EOF) //统计文章的段落
para++;
}
fclose(w);
sprintf(s, "\n段 落:%d\n英文字母:%d个\n空 格:%d个\n数 字 : %d个\n符 号:%d个\n",para,l,m,j,p);
// FILE *write=fopen("hao.txt", "a");
fputs(s, write);
fclose(write);
printf("英文字母:%d个\n", l);
printf("空 格:%d个\n", m);
printf("数 字:%d个\n", j);
printf("符 号:%d个\n", p);
printf("段 落:%d段\n", para);
}
int count_word(char str[])//统计单词个数
{
int num = 0;
int i=0;
for (i = 0; str[i]!= '\0'; i++){
if((str[i]>='A'&&str[i]<='Z')||(str[i]>='a'&&str[i]<='z'))
{
if(str[i+1]==' '||str[i+1]=='.'||str[i+1] =='?'||str[i+1]=='!'||str[i+1]=='\0'||str[i+1]==10)
num++;
}
}
printf("单词个数:%d个\n",num);
return num;
}
int count_zw(char str[])//统计中文
{
int i,h=0;
for (i = 0; i < strlen(str); i++)
{
if((str[i]<='A'||str[i]>='Z')||(str[i]<='a'||str[i]>='b'))
{
if (str[i] < 0&&str[i+1]<0) //汉字对应的ASCLL值为负
{
h++;
i++; //汉字占两个字符,所以i要加两次
}
}
}
printf("汉 字%d个\n", h);
return h;
}