实验结论:
clear()用于清空stringstream内容
str(“”)用于释放stringstream内存
最好两个一起使用
#include <sstream>
#include <iostream>
using namespace std;
/*
使用stringstream进行数据转型时,必须用clear()清空stringstream的内容,但只用clear()并不释放内存,在clear()后使用str("")可以释放其内存资源
实验结论:
clear()用于清空stringstream内容
str("")用于释放stringstream内存
*/
int main()
{
stringstream sstream;
int first, second;
// 插入字符串
sstream << "456";
// 转换为int类型
sstream >> first;
// cout << "used clear(): " << first << endl; // 456
// cout << "unused clear(): " << first << endl; // 456
// cout << "used .str(''): " << first << endl; // 456
cout << "used .str(): Size of stream = " << sstream.str().length() << endl; // 3
// 在进行多次类型转换前,必须先运行clear()
sstream.clear();
sstream.str("");
// cout << "Unused .str(): Size of stream = " << sstream.str().length() << endl; // 3
cout << "used .str(): Size of stream = " << sstream.str().length() << endl; // 0
// 插入bool值
// sstream << true;
sstream << "789";
// 转换为int类型
sstream >> second;
// cout << "Unused .str():Size of stream = " << sstream.str().length() << endl; // 6
cout << "used .str():Size of stream = " << sstream.str().length() << endl; // 3
// cout << "used clear(): " << second << endl; // 1
// cout << "unused clear(): " << second << endl; // 216572660
// cout << "used .str(''): " << second << endl; // 216849752
system("pause");
return 0;
}