C++ 读取文件并统计字符数、行数和单词数

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

bool isnum_str(char str)  //判断是否是字符或数字
{
  if((str >= 'A' && str <= 'z') || (str >= '0' && str <= '9') )
	  return true;
  else
	  return false;
}

void count(fstream &outfile, int *cnt )  //统计函数
{ char str[256];
  while(outfile.getline(str,256))
  { 
    int tmp = 0;
    
    for(int i = 0; i < strlen(str); i++)
	{
	  if(str[i] == ' ' || str[i] == '.' || str[i] == ',' || str[i] == '?' || str[i] == '!')
		  cnt[1]++;            //统计单词数
	  
	  if(isnum_str(str[i]))
	  { cnt[0]++;   tmp++;}    //统计字符数,tmp局部变量用来区分是不是一个空行。
	}
	
	if(tmp != 0)
	cnt[2]++;                 //统计行数
	tmp = 0;
  }
    
 return ;
}

int main()
{
    char filename[256];
    int cnt[3] = {0};
    
    
    cout<<"please input your filename:"<<endl; //输入要统计的文本的绝对路径
    cin.getline(filename,256);
	
    fstream outfile(filename,ios::in);
    count(outfile,cnt);
    //outfile<<"character:"<<cnt[0]<<"words:"<<cnt[1]<<"lines:"<<cnt[2]<<endl; //不知道这一行为啥输入不到文本,期待学习
	cout<<"characters: "<<cnt[0]<<endl;
	cout<<"words:"<<cnt[1]<<endl;
	cout<<"lines:"<<cnt[2]<<endl;
    outfile.close();
    system("pause");
  return 0;    

system("pause");
return 0;

}


总结:学习了C++中的输入输出流类 。更多参考: 点击打开链接。功能要需要进一步加强。
  • 6
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值