这四个是 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 | 字符串输出流 | 写入内存字符串 | 把数据拼接成字符串(格式化拼接) |