第十四周项目1-3:统计字符个数

来源:互联网 发布:亨德尔 水上音乐 知乎 编辑:程序博客网 时间:2024/06/06 04:14

问题及代码:

/**Copyright (c)2015,烟台大学计算机与控制工程学院*All rights reserved.*文件名称:test.cpp*作    者:陈文青*完成日期:2015年6月16日*版 本 号:v1.0**问题描述:用键盘输入文件名,统计输出文件中每个字母、数字字符出现的次数;*程序输入:*程序输出:*/#include <iostream>#include <cstdlib>#include <fstream>using namespace std;int main(){    fstream file;    int count1=0,count2=0;     //分别用来统计英文字符、数字字符    char fname[20];            //用作存放文件名    char c;                    //用作统计字符    cout<<"请输入文件名(文件名.扩展名):";    cin>>fname;    file.open(fname,ios::in);  //以输入方式打开文件    if(!file)                  //如果打开失败    {        cout<<"Can't open the file."<<endl;        exit(1);    }    while(file.get(c))         //统计字符    {        if((c>='A'&&c<='Z')||(c>='a'&&c<='z'))            count1++;        else if(c>='0'&&c<='9')            count2++;    }    file.close();             //关闭文件    cout<<"文件中字母出现"<<count1<<"次,"<<"数字字符出现"<<count2<<"次"<<endl;    return 0;}

运行结果:



知识点总结:

利用文件流统计字符个数

0 0