今天在用stringstream做数据转换的时候,遇到了问题,发现得到的不是预期的结果。
简化的代码如下:
#include <cstdlib> #include <iostream> #include <sstream> using namespace std; int main(int argc, char * argv[]) { stringstream stream; int a,b; stream<<"80"; stream>>a; stream<<"90"; stream>>b; cout<<a<<endl; cout<<b<<endl; system("PAUSE "); return EXIT_SUCCESS; }
运行结果:
int变量b预期的到的结果应该是90,但是程序运行的结果却是-858993460这样一个数据,显然是哪里错了。
于是,google一番之后,原因是,stringstream重复使用时,因为没有清空导致的问题。看到一种解决方案:再次使用前,使用stringstream.clear()清空。
测试代码:
#include <cstdlib> #include <iostream> #include <sstream> using namespace std; int main(int argc, char * argv[]) { stringstream stream; int a,b; stream<<"80"; stream>>a; stream.clear();// stream<<"90"; stream>>b; cout<<a<<endl; cout<<b<<endl; system("PAUSE "); return EXIT_SUCCESS; }
运行结果:
果然,我们得到预期的结果了。
但是,stringstream.clear()是什么呢?
void clear ( iostate state = goodbit );
Set error state flags
Sets a new value for the error control state.
All the bits in the control state are replaced by the new ones; The value existing before the call has no effect.
If the function is called with goodbit as argument (which is the default value) all error flags are cleared.
The current state can be obtained with member function rdstate.
clear清空的的标志位!!看下面代码运行的结果:
#include <cstdlib> #include <iostream> #include <sstream> using namespace std; int main(int argc, char * argv[]) { stringstream stream; int a,b; stream<<"80"; stream>>a; stream.clear(); cout<<"Size of stream = "<<stream.str().length()<<endl; stream<<"90"; stream>>b; cout<<"Size of stream = "<<stream.str().length()<<endl; cout<<a<<endl; cout<<b<<endl; system("PAUSE "); return EXIT_SUCCESS; }
运行结果:
clear()之后,虽然结果正确了,但是stream占用的内存却没有释放!!!在我们的小测试中虽然不会有什么问题,但是在实际的应用中,要是多次使用stringstream,每次都增加占用的内存,那么显然是会有问题的!!!
继续google之后,stringstream.str()出现了。
void str ( const string & s ); // copies the content of string s to the string object associated with the string stream buffer. The function effectivelly calls rdbuf()->str(). Notice that setting a new string does not clear the error flags currently set in the stream object unless the member function clear is explicitly called.
可以利用stringstream.str("")来清空stringstream。
测试代码:
#include <cstdlib> #include <iostream> #include <sstream> using namespace std; int main(int argc, char * argv[]) { stringstream stream; int a,b; stream<<"80"; stream>>a; cout<<"Size of stream = "<<stream.str().length()<<endl; stream.clear(); stream.str(""); cout<<"Size of stream = "<<stream.str().length()<<endl; stream<<"90"; stream>>b; cout<<"Size of stream = "<<stream.str().length()<<endl; cout<<a<<endl; cout<<b<<endl; system("PAUSE "); return EXIT_SUCCESS; }
运行结果:
总结一下吧,
void clear ( iostate state = goodbit );//该方法绝非清空stringstream中的内容,而是清空该流的错误标记!
void str ( const string & s );//该方法是重新给stringstream赋新值的意思。
于是,我们轻松愉快的解决了问题,么么哒。