04 | c++<sstream>带给我们的优雅
问题导向
我们想要把各种不同的数据类型输出的话?
就算是用printf也避免不了%d,%s等等复杂的东西。
我们的愿望?
有这样一个类似容器的东西,不管是什么基本类型只要丢进去就会自动转化为字符串那太好了。有种万众归一的感觉。
概述
三个主要用途
数据类型转换
#include
#include
#include
#include
using namespace std;
int main()
{
stringstream sstream;
string strResult;
int nValue = 1000;
// 将int类型的值放入输入流中
sstream << nValue;
// 从sstream中抽取前面插入的int类型的值,赋给string类型
sstream >> strResult;
cout << "[cout]strResult is: " << strResult << endl;
printf("[printf]strResult is: %s\n", strResult.c_str());
return 0;
}
多个字符串的拼接
本示例介绍在 stringstream 中存放多个字符串,实现多个字符串拼接的目的(其实完全可以使用 string 类实现),同时,介绍 stringstream 类的清空方法。
#include
#include
#include
using namespace std;
int main()
{
stringstream sstream;
// 将多个字符串放入 sstream 中
sstream << "first" << " " << "string,";
sstream << " second string";
cout << "strResult is: " << sstream.str() << endl;
// 清空 sstream
sstream.str("");
sstream << "third string";
cout << "After clear, strResult is: " << sstream.str() << endl;
return 0;
}
从上述代码执行结果能够知道:
- 可以使用 str() 方法,将 stringstream 类型转换为 string 类型;
- 可以将多个字符串放入 stringstream 中,实现字符串的拼接目的;
- 如果想清空 stringstream,必须使用 sstream.str(""); 方式;clear() 方法适用于进行多次数据类型转换的场景。
stringstream的清空
清空 stringstream 有两种方法:clear() 方法以及 str("") 方法,这两种方法对应不同的使用场景。str("") 方法的使用场景,在上面的示例中已经介绍过了,这里介绍 clear() 方法的使用场景。
#include
#include
using namespace std;
int main()
{
stringstream sstream;
int first, second;
// 插入字符串
sstream << "456";
// 转换为int类型
sstream >> first;
cout << first << endl;
// 在进行多次类型转换前,必须先运行clear()
sstream.clear();
// 插入bool值
sstream << true;
// 转换为int类型
sstream >> second;
cout << second << endl;
return 0;
}
注意:在本示例涉及的场景下(多次数据类型转换),必须使用 clear() 方法清空 stringstream,不使用 clear() 方法或使用 str("") 方法,都不能得到数据类型转换的正确结果。下图分别是未使用 clear() 方法、使用 str("") 方法代替 clear() 方法时的运行结果:
参考
https://blog.csdn.net/liitdar/article/details/82598039?