std::stringstream类的用法
时间: 2023-08-04 16:06:45 浏览: 55
std::stringstream 是 C++ 标准库中的一个类,它提供了将数据以字符串的形式读入和输出的功能。下面是一个简单的示例:
```
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::stringstream ss;
std::string str = "Hello, World!";
int num = 42;
// 将字符串和整数写入 stringstream
ss << str << " " << num;
// 从 stringstream 读取字符串和整数
std::string str_out;
int num_out;
ss >> str_out >> num_out;
std::cout << "String: " << str_out << std::endl;
std::cout << "Integer: " << num_out << std::endl;
return 0;
}
```
上述代码中,我们首先创建了一个名为 `ss` 的 stringstream 对象,然后使用 `<<` 运算符将一个字符串和一个整数写入 stringstream 中。接下来,我们使用 `>>` 运算符从 stringstream 中读取字符串和整数,并将它们存储在 `str_out` 和 `num_out` 变量中。最后,我们将读取到的数据输出到标准输出中。
需要注意的是,在从 stringstream 中读取数据时,我们需要使用 `>>` 运算符,并且读取的顺序应该与写入的顺序相同,否则读取到的数据可能会出现错误。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)