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

首頁 > 編程 > 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; 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 湖口县| 繁昌县| 定兴县| 合江县| 永泰县| 林甸县| 双辽市| 聊城市| 珲春市| 白沙| 桐城市| 安吉县| 崇明县| 东明县| 云安县| 郯城县| 茂名市| 通榆县| 酒泉市| 增城市| 岳西县| 兴城市| 长沙市| 周至县| 沂源县| 大田县| 卓尼县| 文水县| 新郑市| 鄄城县| 海宁市| 台州市| 武夷山市| 成武县| 曲阳县| 甘洛县| 桦甸市| 晋中市| 苍南县| 临猗县| 云霄县|