问题及代码:
运行结果:
/*
*Copyright (c)2015,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:File.cpp
*作 者:单昕昕
*完成日期:2015年6月8日
*版 本 号:v1.0
*问题描述:用键盘输入文件名,统计输出文件中每个字母、数字字符出现的次数。
*程序输入:文件读取。
*程序输出:文件中每个字母、数字字符出现的次数。
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>//为了使用exit()
#include <fstream>
using namespace std;
int main()
{
char ch;
int count1=0,count2=0;//分别用来统计英文字符、数字字符
FILE *fp=NULL;
char fname[50];//用于存放文件名
cout<<"请输入文件名(请注意加上文件名后缀):";
gets(fname);
fp=fopen(fname,"r");//只供读取
if(fp==NULL)//如果失败了
{
cout<<"文件打开错误!";
exit(1);//中止程序
}
while((ch=getc(fp))!=EOF)
{
putchar(ch);
if((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z'))
count1++;
else if(ch>='0'&&ch<='9')
count2++;
}
fclose(fp);//关闭文件
fp=NULL;//需要指向空,否则会指向原打开文件地址
cout<<endl;
cout<<"文件中每个字母出现"<<count1<<"次,"<<"数字字符出现"<<count2<<"次"<<endl;
return 0;
}
运行结果:
知识点总结:
主要是学会了fopen的用法。
学习心得:
去百度上自学的,感觉很成功,还不错的样子~~~新新技能get~~