当前位置: 首页 > news >正文

c++函数式编程:统计文件字符串,文件流

头文件

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>

统计方法

int count_lines(const std::string &filename)
{std::ifstream in{filename};return std::count(std::istreambuf_iterator<char>{in},std::istreambuf_iterator<char>{},'\n');
}

std::istreambuf_iterator

读取输入缓冲区,板参数只能是char和wchar_t类型,std::istreambuf_iterator{}即默认构造的为end,例子如下

读取字符串

void readString()
{std::istringstream ins{"abcd"};std::string str(std::istreambuf_iterator<char>{ins},std::istreambuf_iterator<char>{});std::cout<<str<<std::endl;
}

扩展:istringstream类用于执行C++风格的串流的输入操作

例子:分割被空格、制表符等符号分割的字符串,类型转换

    std::istringstream ins{"123 456 789"};int nTmp = 0;while(ins >> nTmp){std::cout<<nTmp<<std::endl;}

扩展:ostringstream 类用于执行C风格的串流的输出操作

void writeString()
{std::ostringstream os{"123 456",std::ios_base::ate};os << " 789";std::cout<<os.str()<<std::endl;
}

扩展: stringstream类同时可以支持C风格的串流的输入输出操作

void readwriteString()
{std::stringstream streeam;streeam << "123 ";streeam << "789";int nTmp = 0;while(streeam >> nTmp){std::cout<<nTmp<<std::endl;}std::cout<<streeam.str()<<std::endl;
}

读取所文件所有内容到字符串,包括\n等空白字符

void readAllText(const std::string &filename)
{std::ifstream in{filename};std::string str(std::istreambuf_iterator<char>{in},std::istreambuf_iterator<char>{});std::cout<<str<<std::endl;
}

读取所文件所有内容到容器,包括\n等空白字符

void readAllTextVec(const std::string &filename)
{std::ifstream in{filename};std::vector<char> vec{std::istreambuf_iterator<char>{in},std::istreambuf_iterator<char>{}};std::cout<<vec.size()<<std::endl;
}

有重载++、*

void readAllTextCount(const std::string &filename)
{unsigned int nCount = 0;std::ifstream in{filename};std::istreambuf_iterator<char>  it{in},end;for(;it != end;it++){if(*it == '\n'){nCount++;}}std::cout<<"nCount:"<<nCount<<std::endl;
}
http://www.lryc.cn/news/100948.html

相关文章:

  • scp命令----跨服务器传输文件
  • React Dva项目中模仿网络请求数据方法
  • 【云原生】Docker容器命令监控+Prometheus监控平台
  • DBA 职责及日常工作职责
  • 如何利用量化接口进行数据分析和计算?
  • electron-egg 加密报错
  • 循环队列的基本操作(3种处理方式,2种实现方式)
  • react的特点
  • MATLAB实现图像处理:图像识别、去雨、去雾、去噪、去模糊等等(附上20个完整仿真源码)
  • cmake stm32 模板
  • STM32 UDS Bootloader开发-上位机篇-CANoe制作(2)
  • 实例026 随机更换主界面背景
  • PostgreSQL 简洁、使用、正排索引与倒排索引、空间搜索、用户与角色
  • querySubObject(“Cells(int,int)“, j,i)->property(“Value“)读不到数据问题
  • AutoSAR系列讲解(实践篇)10.2-EcuM的上下电流程
  • 科研院所用泛微搭建信创办公平台,统一办公,业务融合,安全便捷
  • 基于LoRA进行Stable Diffusion的微调
  • C++STL序列式容器——list容器及其常用操作(详解)
  • 【雕爷学编程】MicroPython动手做(15)——掌控板之AB按键2
  • Spring Boot中整合MyBatis(基于xml方式基于注解实现方式)
  • ChatGPT漫谈(三)
  • 树、二叉树(C语言版)详解
  • vue中Cascader 级联选择器实现-修改实现
  • C语言实现三子棋游戏
  • 机器学习深度学习——softmax回归从零开始实现
  • Windows如何安装Django及如何创建项目
  • 在CSDN学Golang云原生(监控解决方案Prometheus)
  • 双重for循环优化
  • golang利用go mod巧妙替换使用本地项目的包
  • 使用 docker 一键部署 MySQL