浅谈stringstream 的.str()正确用法和清空操作
时间: 2023-08-29 11:03:08 浏览: 137
stringstream 是一个可以进行输入和输出操作的流,它可以方便地将不同类型的数据转换为字符串,并且可以对字符串进行解析。
在使用 stringstream 的过程中,我们常常会用到它的 .str() 函数。该函数的作用是将 stringstream 对象中的数据转换为字符串类型并返回。例如:
```
#include <iostream>
#include <sstream>
int main() {
std::stringstream ss;
int num = 123;
ss << num;
std::string str = ss.str();
std::cout << str << std::endl;
return 0;
}
```
上述代码中,我们将一个整数 num 插入到了 stringstream 对象 ss 中,并通过 .str() 函数将 ss 中的数据转换为字符串类型并赋值给了 str 变量。然后我们通过输出流将 str 打印出来,结果为 "123"。
另外,如果想要清空 stringstream 对象中的数据,我们可以使用 .str("") 的方式进行清空操作。例如:
```
#include <iostream>
#include <sstream>
int main() {
std::stringstream ss;
int num = 123;
ss << num;
std::cout << ss.str() << std::endl; // 输出 "123"
ss.str(""); // 清空 ss 中的数据
std::cout << ss.str() << std::endl; // 输出空字符串
return 0;
}
```
上述代码中,我们先将 num 插入到了 ss 中并通过输出流打印出来,然后通过 ss.str("") 清空了 ss 中的数据。此时再次通过输出流打印出来的结果为空字符串。
综上所述,.str() 函数的正确用法是将 stringstream 对象中的数据转换为字符串返回,而清空操作可以通过 ss.str("") 完成。
相关推荐
![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)