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 字符串输出流 写入内存字符串 把数据拼接成字符串(格式化拼接)
相关推荐
-银雾鸢尾-6 小时前
C#中的StringBuilder相关方法
开发语言·c#
To_OC6 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
Henry Zhu1236 小时前
C++中的特殊成员函数与智能指针
c++
delishcomcn7 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹7 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
大模型码小白7 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
雪碧聊技术8 小时前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
_wyt0019 小时前
多重背包问题详解
c++·背包dp
段一凡-华北理工大学9 小时前
向量数据库实战:选型、调优与落地~系列文章12:文本分块策略实战:chunk_size 怎么选?重叠多少?
开发语言·数据库·后端·oracle·rust·工业智能体·高炉智能化