C++(流类:istream /ostream/istringstream /ostringstream)

这四个是 C++ 标准输入输出流的核心类,都属于 <iostream> 和 <sstream> 库,专门处理数据的输入 / 输出,区别只在于数据来源 / 去向不同。

1. 基础流类:istream / ostream

这两个是所有输入 / 输出流的基类,我们天天用的 cin / cout 就是它们的实例:

istream:输入流,负责读取数据

ostream:输出流,负责写入数据

cpp 复制代码
class Int {
	int value;
public:
	Int(int x=0):value(x){}
	void SetValue(int x) { value = x; }
	int GetValue()const { return value; }
	void Print()const { cout << "value:" << value << endl; }
	int& Value(){ return value; }
	const int& Value() const{ return value; }

};
std::istream & operator>>(std::istream& in, Int& it) {//写入没有常性
		in >> it.Value();
		return in;
}
std::ostream& operator<<(std::ostream& out,const Int& it) {//读取有常性
	   out << it.Value();
	   return out;
}
int main() {
	Int a(10),b(20);
	a.Print();
	cin >> a >> b;
	a.Print();
	b.Print();
	cout << a << " " << b;
}

2. 字符串流:istringstream / ostringstream

这两个是专门操作内存中字符串 的流,不读写键盘 / 屏幕,只读写字符串变量 ,必须包含头文件 <sstream>

(1) istringstream:字符串 → 数据(解析字符串)

作用:把一个字符串当成「输入源」,从中提取各种类型的数据(拆分字符串、类型转换)。

场景:字符串分割、把字符串转成数字。

cpp 复制代码
#include <iostream>
#include <sstream>  // 必须包含
#include <string>
using namespace std;

int main() {
    string str = "100 200 3.14 hello";
    istringstream iss(str);  // 用字符串初始化输入流

    int a, b;
    double c;
    string d;

    // 从字符串中「读取」数据,和 cin 用法完全一样
    iss >> a >> b >> c >> d;  

    cout << a << " " << b << " " << c << " " << d << endl;
    // 输出:100 200 3.14 hello
    return 0;
}

(2)ostringstream:数据 → 字符串(拼接字符串)

作用:把各种类型的数据「写入」流中,最后合并成一个完整字符串。

场景 :格式化字符串、多类型数据拼接(替代繁琐的 + 拼接)。

cpp 复制代码
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
    ostringstream oss;  // 创建输出流
    int age = 20;
    double score = 95.5;
    string name = "张三";

    // 向流中「写入」数据,和 cout 用法完全一样
    oss << "姓名:" << name << ",年龄:" << age << ",分数:" << score;

    // 用 str() 方法获取最终拼接好的字符串
    string result = oss.str();  
    cout << result << endl;
    // 输出:姓名:张三,年龄:20,分数:95.5
    return 0;
}

完美的对比表格:

类名 父类 作用 数据来源 / 去向 核心用途
istream 基类 输入流(只读) 键盘、文件、设备 从外部读取数据(cin 就是它)
ostream 基类 输出流(只写) 屏幕、文件、设备 向外部输出数据(cout 就是它)
istringstream 继承 istream 字符串输入流 内存中的字符串 把字符串拆成数据(字符串解析)
ostringstream 继承 ostream 字符串输出流 写入内存字符串 把数据拼接成字符串(格式化拼接)
相关推荐
倒头就睡的小比特2 天前
算法竞赛C++常用的STL
c++·算法
weilx12342 天前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!2 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
猎头南楼2 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
Smileyqp沛沛2 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车2 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光2 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark2 天前
大规模并行计算中的负载均衡算法研究4
算法
吞下星星的少年·-·2 天前
C++ 萌新语法入门篇
c++·算法比赛