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++ 工厂模式:从入门到进阶,彻底掌握对象创建的艺术
开发语言·c++·算法
@insist1232 小时前
系统架构设计师-实时性评价、调度算法与内核架构选型
算法·架构·系统架构·软考·系统架构设计师·软件水平考试
JosieBook3 小时前
【数据库】时序预测能力的分级进化:TimechoAI如何让每一类用户都能精准预见未来
java·开发语言·数据库
加号33 小时前
【C#】 文件与目录管理:创建、删除操作的技术解析
开发语言·c#
diving deep4 小时前
脚本速览-python
开发语言·python
一生了无挂4 小时前
Java处理JSON技巧教学(从基础到高阶实战全覆盖)
java·开发语言·json
swordbob4 小时前
Spring 单例 Bean 是线程安全的吗?
java·开发语言
一拳一个呆瓜5 小时前
【STL】_SCL_SECURE_NO_WARNINGS
c++·stl
小小编程路5 小时前
C++ 异常 完整讲解
开发语言·c++