#include <sstream>

`#include <sstream>` 是 C++ 标准库中的一个头文件,它提供了一些类和函数,使得我们可以在内存中操��字符串就像操作输入/输出流一样。这些类和函数都在 `std` 命名空间中。主要的类有 `std::stringstream`、`std::istringstream` 和 `std::ostringstream`。

1. `std::stringstream`:这个类可以同时进行输入和输出操作。你可以像流一样向其写入数据,然后再从中读取数据。

```cpp
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
    stringstream ss;
    ss << "Hello, " << "World! " << 123;
    string s = ss.str();
    cout << s << endl;  // 输出:Hello, World! 123
    return 0;
}
```

2. `std::istringstream`:这个类主要用于从字符串中读取数据。你可以将一个字符串传递给它的构造函数,然后像从流中读取数据一样从字符串中读取数据。

```cpp
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
    string s = "Hello World 123";
    istringstream iss(s);
    string word;
    int num;
    iss >> word;  // word 现在是 "Hello"
    iss >> word;  // word 现在是 "World"
    iss >> num;   // num 现在是 123
    cout << word << " " << num << endl; // 输出:World 123
    return 0;
}
```

3. `std::ostringstream`:这个类主要用于向字符串中写入数据。你可以像向流中写入数据一样向字符串中写入数据。

```cpp
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
    ostringstream oss;
    oss << "Hello, " << "World! " << 123;
    string s = oss.str();
    cout << s << endl;  // 输出:Hello, World! 123
    return 0;
}
```

总的来说,`<sstream>` 提供了一种方便的方式来处理字符串,特别是当你需要进行复杂的字符串操作,如解析或格式化字符串时,这个库会非常有用。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值