首页 > 编程 > C++ > 正文

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

2020-05-23 14:14:22
字体:大 中 小
来源:转载
供稿:网友

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

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

 

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

网上大神的简单代码

 

  1. #include<iostream> 
  2. #include<fstream> 
  3. using namespace std; 
  4. int main() 
  5. { 
  6. fstream f("test.txt",ios::in); 
  7. char c; 
  8. int n=0; 
  9. while(f.get(c))n++; 
  10. cout<<n<<endl; 
  11. f.close();  
  12. return 0;  
  13. } 

上面那方法会计算空格和换行,如果不想要换行和空格,可以这样:

 

 
  1. #include<iostream> 
  2. #include<fstream> 
  3. using namespace std; 
  4. int main() 
  5. { 
  6. fstream f("test.txt",ios::in); 
  7. char c; 
  8. int n=0; 
  9. while(f>>c)n++; 
  10. cout<<n<<endl; 
  11. f.close();  
  12. return 0;  
  13. } 

好了,最后来看一下项目中使用到的代码

 

 
  1. //countch.cpp 
  2. #include <iostream> 
  3. #include <fstream> 
  4. #include <string> 
  5.  
  6. using namespace std; 
  7.  
  8. int main(int argc, char* argv[]) 
  9. { 
  10. ifstream fin(argv[1]); 
  11. if (!fin) { 
  12. cout << "Can't open file - " << argv[1]  
  13. << "/nUseage : countch filename" << endl; 
  14. return 1; 
  15. } 
  16.  
  17. string d; 
  18. int count = 0; 
  19. while ( getline(fin, d) ) //以行为单位读入文件 
  20. count += d.size(); //累计字符数 
  21.  
  22. cout << "/n Number of characters : "<< count << endl; 
  23. } 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表