c++统计文件中字符个数代码汇总

2020-01-06 13:44:24王冬梅

本文给大家汇总介绍了3种使用C++实现统计文件中的字符个数的方法,非常的简单实用,有需要的小伙伴可以参考下。

我们先来看看下面的代码:

 

 
  1. #include<iostream>  #include<fstream> 
  2. #include<cstdlib>  using namespace std; 
  3. class CntCharacters  { 
  4. private:  int cnt; 
  5. public:  CntCharacters():cnt(0){} 
  6. ~CntCharacters(){}  void opentxt(char* p) 
  7. {  ifstream fin; 
  8. fin.open(p,ios_base::in);  if(!fin.is_open()) 
  9. {  cout<<"cannot open the file,Please make sure the file is exist!n"; 
  10. exit(-1);  } 
  11. char temp;  while(!fin.eof()) 
  12. {  fin>>temp; 
  13. if((temp>='a'&&temp<='z')||(temp>='A'&&temp<='Z'))cnt++;  } 
  14. }  void countthecharacter() 
  15. {  int count=0; 
  16. char nameoffile[80];  cout<<"Please enter the name of file:"; 
  17. cin>>nameoffile;  // scanf("%s",nameoffile); 
  18. opentxt(nameoffile);  } 
  19. void dis()  { 
  20. cout<<cnt<<endl;  } 
  21. };  int main() 
  22. {  CntCharacters* c=new CntCharacters; 
  23. c->countthecharacter();  c->dis(); 
  24. delete c;  return 0;