国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

c++統(tǒng)計文件中字符個數(shù)代碼匯總

2020-01-26 14:51:08
字體:
來源:轉載
供稿:網(wǎng)友

我們先來看看下面的代碼:

#include<iostream>#include<fstream>#include<cstdlib>using namespace std;class CntCharacters{private:  int cnt;public:  CntCharacters():cnt(0){}  ~CntCharacters(){}  void opentxt(char* p)  {    ifstream fin;    fin.open(p,ios_base::in);    if(!fin.is_open())    {     cout<<"cannot open the file,Please make sure the file is exist!/n";     exit(-1);    }    char temp;    while(!fin.eof())    {     fin>>temp;     if((temp>='a'&&temp<='z')||(temp>='A'&&temp<='Z'))cnt++;    }  }  void countthecharacter()  {   int count=0;   char nameoffile[80];   cout<<"Please enter the name of file:";   cin>>nameoffile;  //  scanf("%s",nameoffile);   opentxt(nameoffile);  }  void dis()  {   cout<<cnt<<endl;  }};int main(){  CntCharacters* c=new CntCharacters;  c->countthecharacter();  c->dis();  delete c;return 0;}

網(wǎng)上大神的簡單代碼

#include<iostream>#include<fstream>using namespace std;int main(){  fstream f("test.txt",ios::in);  char c;  int n=0;  while(f.get(c))n++;  cout<<n<<endl;  f.close();   return 0; }

上面那方法會計算空格和換行,如果不想要換行和空格,可以這樣:

#include<iostream>#include<fstream>using namespace std;int main(){  fstream f("test.txt",ios::in);  char c;  int n=0;  while(f>>c)n++;  cout<<n<<endl;  f.close();   return 0; }

好了,最后來看一下項目中使用到的代碼

//countch.cpp#include <iostream>#include <fstream>#include <string>using namespace std;int main(int argc, char* argv[]){  ifstream fin(argv[1]);  if (!fin) {    cout << "Can't open file - " << argv[1]       << "/nUseage : countch filename" << endl;    return 1;  }    string d;  int count = 0;  while ( getline(fin, d) ) //以行為單位讀入文件    count += d.size(); //累計字符數(shù)    cout << "/n Number of characters : "<< count << endl;}

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 石屏县| 商南县| 陈巴尔虎旗| 永定县| 福贡县| 苏尼特右旗| 延长县| 辛集市| 磐石市| 阿巴嘎旗| 天全县| 兰考县| 齐河县| 永新县| 溧水县| 嘉荫县| 独山县| 长垣县| 卢湾区| 渭南市| 拜泉县| 汕头市| 陇南市| 克东县| 英吉沙县| 霍林郭勒市| 舒城县| 永丰县| 突泉县| 桑日县| 张家界市| 隆子县| 万荣县| 万源市| 桂林市| 霸州市| 舒城县| 手机| 集贤县| 泉州市| 巴里|