stringstream 是 C++ 提供的一个字串型的串流(stream)物件。相比c库的转换,它更加安全,自动和直接。
用法
头文件
要想使用stringstream,首先要包含头文件 sstream
#include <sstream>
类型转换
stringstream可以进行 int 和 string 两种类型的互换。样例如下:
#include<iostream>
#include<sstream> //istringstream 必须包含这个头文件
#include<string>
using namespace std;
int main(){
string str="i am a boy";
istringstream is(str);
string s;
while(is>>s) {
cout<<s<<endl;
}
}
输出结果:
buf1 = 7 n = 7
n = -10
test1
分离单词
ss可以将输入的一段字符串按照空白来切分。如以下示例
#include<iostream>
#include<sstream> //istringstream 必须包含这个头文件
#include<string>
using namespace std;
int main(){
string str="i am a boy";
istringstream is(str);
string s;
while(is>>s) {
cout<<s<<endl;
}
}
一些坑
stream.str(""))
如果你希望一个ss对象使用多次,那么你可能需要这个函数。
stringstream构造函数会特别消耗内存,似乎不打算主动释放内存(或许是为了提高效率),但如果你要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消耗,因些这时候,需要适时地清除一下缓冲。
可以用以下代码做测试:
#include <cstdlib>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
std::stringstream stream;
string str;
while (1)
{
//clear(),这个名字让很多人想当然地认为它会清除流的内容。
//实际上,它并不清空任何内容,它只是重置了流的状态标志而已!
stream.clear();
// 去掉下面这行注释,清空stringstream的缓冲,每次循环内存消耗将不再增加!
//stream.str("");
stream << "sdfsdfdsfsadfsdafsdfsdgsdgsdgsadgdsgsdagasdgsdagsadgsdgsgdsagsadgs ";
stream >> str;
// 去掉下面两行注释,看看每次循环,你的内存消耗增加了多少!
//cout<<"Size of stream = "<<stream.str().length()<<endl;
//system("PAUSE");
}
system("PAUSE ");
return 0;
}
今天做题只碰到了这些,以后碰到更多再记录下来吧。