zoukankan      html  css  js  c++  java
  • 【c++ primer读书笔记】【第8章】IO流

    1、iostream定义了读写流的基本类型,fstream定义了读写命名文件的类型,sstream定义了读写string对象的类型。

    头文件

    类型

    iostream

    istream, wistream从流读取数据

    ostream, wostream向流写入数据

    iostream, wiostream读写流

    fstream

    ifstream, wifstream从文件读取数据

    ofstream, wofstream向文件写入数据

    fstream, wfstream读写文件

    sstream

    istringstream, wistringstream从string读取数据

    ostringstream, wostringstream向string写入数据

    stringstream, wstringstream读写string

    2、IO对象不能拷贝或赋值,不能将形参或返回类型设置为流类型;读写IO对象会改变其状态,因此传递和返回的IO对象的引用不能是const的。

    3、IO类定义了一些函数和标志,可以用来访问和操作流的条件状态。

    4、刷新输出缓冲区

    cout << "hi" << endl; //输出hi和一个换行,然后刷新缓冲
    cout << "hi" << flush; //输出hi,然后刷新缓冲,不添加数据
    cout << "hi" << ends; //输出hi 和一个空字符,然后刷新缓冲
    

    unitbuf操纵符:告诉流在接下来的每次写操作之后都进行一次flush操作

    cout<<unitbuf; //所有输出操作后都会立即刷新缓冲区
    cout<<nounitbuf; //回到正常的缓冲方式

    5、string流

    istringstream从string读取数据,ostringstream向string写入数据,stringstream既可以从string读取数据也可以向string写入数据

    将一个data.txt文件中的行保存在一个vector<string>中,然后用istringstream从vector读取数据元素,每次读取一个整数并求和。data.txt里的数据如下:

    1 2 3 4
    5 6 7
    8 9
    10
    完整程序如下:

    #include<iostream>
    #include<string>
    #include<sstream>
    #include<vector>
    #include<fstream>
    using namespace std;
    
    int main(){
    	string line;
    	vector<string> vec;
    	int sum=0;
    	
    	ifstream file("data.txt");
    	while(getline(file,line))
    	     vec.push_back(line);
    
    	for(auto& l:vec){
    	     istringstream is(l);
    	     int word;
    	     while(is>>word)
    		 sum+=word;
    	}
    	cout<<sum<<endl;
    
    	system("pause");
    	return 0;
    }
    
    程序运行结果:


  • 相关阅读:
    python实战===python程序打包成exe
    python基础===100盏灯的问题
    安全测试===dos攻击和ddos攻击
    Ubuntu16.04安装Consul
    kerberos相关
    Linux终端复制粘贴后前后会多出0~和~1
    Superset配置impala数据源
    Airflow使用指南
    Superset配置hive数据源
    Superset配置mysql数据源
  • 原文地址:https://www.cnblogs.com/ruan875417/p/4495574.html
Copyright © 2011-2022 走看看