首页 > 编程 > 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. private
  7. int cnt; 
  8. public
  9. CntCharacters():cnt(0){} 
  10. ~CntCharacters(){} 
  11. void opentxt(char* p) 
  12. ifstream fin; 
  13. fin.open(p,ios_base::in); 
  14. if(!fin.is_open()) 
  15. cout<<"cannot open the file,Please make sure the file is exist!/n"
  16. exit(-1); 
  17. char temp; 
  18. while(!fin.eof()) 
  19. fin>>temp; 
  20. if((temp>='a'&&temp<='z')||(temp>='A'&&temp<='Z'))cnt++; 
  21. void countthecharacter() 
  22. int count=0; 
  23. char nameoffile[80]; 
  24. cout<<"Please enter the name of file:"
  25. cin>>nameoffile; 
  26. // scanf("%s",nameoffile); 
  27. opentxt(nameoffile); 
  28. void dis() 
  29. cout<<cnt<<endl; 
  30. }; 
  31. int main() 
  32. CntCharacters* c=new CntCharacters; 
  33. c->countthecharacter(); 
  34. c->dis(); 
  35. delete c; 
  36. return 0; 

网上大神的简单代码

 

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

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

 

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

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

 

 
  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. ifstream fin(argv[1]); 
  10. if (!fin) { 
  11. cout << "Can't open file - " << argv[1]  
  12. << "/nUseage : countch filename" << endl; 
  13. return 1; 
  14.  
  15. string d; 
  16. int count = 0; 
  17. while ( getline(fin, d) ) //以行为单位读入文件 
  18. count += d.size(); //累计字符数 
  19.  
  20. cout << "/n Number of characters : "<< count << endl; 

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