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

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

网上大神的简单代码

 

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

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

 

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