C++标准IO库

来源:互联网 发布:客户特殊要求矩阵图 编辑:程序博客网 时间:2024/06/06 20:46

C++的输入输出是由标准库提供的。标准库提供了很多相关工具:

  • istream (输入流),提供输入操作
  • ostream(输出流),提供输出操作
  • cin,读入标注输入到istream中
  • cout,写入到标准输出的ostream中
  • cerr,输出标准错误到ostream中
  • >> 操作符,从istream中读入输入
  • << 操作符,把输出写到ostream中
  • getline 函数,分别取istream类型和string类型的行参,功能是从istream对象读取一个单词写入到string对象中。

标准IO库结构图

这里写图片描述

平时在使用io库的时候,就是因为没有了解他们的继承关系和使用场合导致无法系统的记忆,现在我们先看下一共有多少种常用的类。
io类型在三个独立的头文件定义,分别完成2中要做的三个事情(控制窗口、磁盘文件、内存)

  • iostream:定义读写控制窗口的类型
  • fstream:定义读写已命名文件的类型。
  • sstream:读写内存中string对象

注意:在fstream和sstream里定义的每种类型都是从iostream头文件中定义的相关类型派生出来,先来看一个图大概了解一下标准io库的成员.
这里写图片描述

代码:

#include <sstream>#include <vector>#include <iostream>using namespace std;vector<int> parseInts(string str) {   // Complete this function    str += ",";   stringstream s(str);   vector<int> result;    int a;    char b;   while(s >> a >> b){       result.push_back(a);   }   return result;}int main() {    string str;    cin >> str;    vector<int> integers = parseInts(str);    for(int i = 0; i < integers.size(); i++) {        cout << integers[i] << "\n";    }    return 0;}
0 0
原创粉丝点击