从键盘输入一段文本,将该文本写入磁盘文件 disk.txt 中,并统计该文本文件中字母、数字、 空白和其它字符的个数,要求将统计结果显示在屏幕上,同时将统计结果写入磁盘文件 total.txt 中。
#include <stdio.h>
int main() {
FILE *diskFile, *totalFile;
char text[1000];
int zm = 0, sz = 0, kb = 0, qt = 0;
fgets(text, sizeof(text), stdin);
diskFile = fopen("disk.txt", "w");
if (diskFile == NULL) {
printf("无法打开磁盘文件 disk.txt\n");
return 1;
}
fprintf(diskFile, "%s", text);
fclose(diskFile);
for (int i = 0; text[i] != '\0'; i++) {
if ((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z')) {
zm++;
} else if (text[i] >= '0' && text[i] <= '9') {
sz++;
} else if (text[i] == ' ' || text[i] == '\t' || text[i] == '\n') {
kb++;
} else {
qt++;
}
}
totalFile = fopen("total.txt", "w");
if (totalFile == NULL) {
printf("无法打开磁盘文件 total.txt\n");
return 1;
}
fprintf(totalFile, "字母个数: %d\n", zm);
fprintf(totalFile, "数字个数: %d\n", sz);
fprintf(totalFile, "空白个数: %d\n", kb);
fprintf(totalFile, "其他字符个数: %d\n", qt);
fclose(totalFile);
printf("字母个数: %d\n", zm);
printf("数字个数: %d\n", sz);
printf("空白个数: %d\n", kb);
printf("其他字符个数: %d\n", qt);
return 0;
}
获取字符串,然后遍历字符串,统计各类字符数后,再写入文件即可。
代码如下:
参考链接:
#include <stdio.h>
#include <ctype.h>
int main(void){
//https://blog.csdn.net/jobfind/article/details/89191265
FILE * fp = fopen("disk.txt","w"); //以写模式打开或创建文件disk.txt
if(fp==NULL){
printf("打开或创建文件失败!\n");
return 0;
}
char ch; //用于临时存储输入的每个字符
int letter=0; //字母字符的个数
int number=0; //数字字符的个数
int space=0; //空白字符的个数
int other=0; //其他字符的个数
printf("请输入一段文本,以回车结束:\n") ;
while((ch=getchar())!='\n'){
fprintf(fp,"%c",ch);
if((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z')){ //判断是否字母字符
letter++;
}else if(ch>='0'&&ch<='9'){// 判断是否为数字字符
number++;
}else if(isspace(ch)){ // 判断是否为空白字符 https://blog.csdn.net/qq_34629352/article/details/106046402
space++;
}else{ //其他字符
other++;
}
}
fclose(fp);
//在屏幕显示统计结果
printf("字母字符个数:%d\n",letter);
printf("数字字符个数:%d\n",number);
printf("空白字符个数:%d\n",space);
printf("其他字符个数:%d\n",other);
fp = fopen("total.txt","w"); //以写模式打开或创建文件total.txt
if(fp==NULL){
printf("打开或创建文件失败!\n");
return 0;
}
//把统计结果写入文件
fprintf(fp,"字母字符个数:%d\n",letter);
fprintf(fp,"数字字符个数:%d\n",number);
fprintf(fp,"空白字符个数:%d\n",space);
fprintf(fp,"其他字符个数:%d\n",other);
fclose(fp);
return 0;
}