C++ Primer学习

IO库

C++ 在IO库中定义的类型支持从键盘、文件、控制台窗口进行输入输出等。

IO类

IO库类型和头文件

头文件类型
iostreamistream/ostream wistream/wostream iostream/wiostream
fstreamifstream/ofstream wifstream/wofstream fstream/wfstream
sstreamistringstream/ostringstream wistringstream/wostringstream stringstream/wstringstream

流类型 stream
文件类型 fstream
字符串类型 sstream


IO类型之间的关系

父类子类
istreamifstream istringstream
ostreamofstream ostringstream

IO对象无拷贝或赋值


IO流的状态
IO库条件状态### 管理输出缓冲
一般原因

  1. 程序正常结束
  2. 缓冲区满
  3. 使用endl
  4. 一个输出流可能被关联到另一个流(输出流或输入流)
  5. unitbuf操作符

文件读写

常用功能

函数功能
fstream f(s.mode)按照指定模式打开文件
f.open(s)打开文件名为s的文件,并将文件与f绑定,返回void
f.close()关闭与f相绑定的文件,返回void
f.is_open()判断文件是否打开,若成功打开,返回True

例程

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *arv[])
{
//write
    ofstream file;
    string path = "1.txt";
    file.open("1.txt");
    if (file.is_open())
    {
        file << "Hello World!";
    }
    else
    {
        cerr << "No data?!" << endl;

    }
    file.close();
//read
    ifstream read_file;
    read_file.open(path, ifstream::in);
    string s;
    if (! read_file.is_open())
    {
        exit(1);
    }
    while (! in.eof())
    {

        s = read_file.
    }
    return 0;
}

每次打开文件完成操作后必须进行关闭,除非在for循环内每次都新定义一个文件对象,那么就不用关闭,文件对象销毁同时则会自动关闭

文件模式

模式说明
in读方式
out写方式
app写操作,定位文件末尾
ate打开文件,定位文件末尾
trunc截断文件
binary以二进制方式进行IO

用法示例

ofstream out("file.txt", ofstream::app)

string类

sstream特有操作

函数说明
sstream strm(s)strm是sstream对象,且保存string s 的一个拷贝
strm.str()返回strm所保存的string的拷贝
strm.str(s)将string s 拷贝到strm中,返回void

istringstream

#例程#

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
struct PersonInfo{
    string name;
    vector<string> phones;
};
    string line, word;
    vector<PersonInfo> people;
    while(getline(cin, line))
    {
        PersonInfo info;
        istringstream record(line);
        record >> info.name;
        while (record >> word)
        {
            info.phones.push_back(word);
        }
        people.push_back(info);
    }
    //得限定字符串输入个数,以便于跳出while循环
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值