C++中stringstream类如何清除缓存

C++编程中,在用stringstream类的库函数将int或double类型转换为string类时,若使用同一个stringstream类对象,常需要将其之前的缓存清空,网上有很多文章说可以调用clear()方法,但我自己尝试过很多遍后发现clear()并没有发挥清空缓存的作用,后来终于在一篇回帖中看到将缓存清空的方法(str()),在此学习一下。
直接上代码(一下程序均在devC++中通过):

先试一下clear()方法

#include
#include
#include
using namespace std;

int main() {
    stringstream stream;
    string b;
    stream.precision(10);  //重设置stream的精度 
    double a = 4.23233;
    stream << a;          //将浮点数a加入缓存
    b = stream.str();     //将缓存中的各种数据转换为string类
    cout << b << endl;
    stream.clear();      //调用clear()方法
    double aa = 2.3;
    stream << aa;        //将浮点数aa加入缓存
    b = stream.str();    //将缓存中的各种数据转换为string类

    cout << b;
} 

运行结果为:

4.23233
4.232332.3
可见clear()并有将stream对象的缓存清空!


再用str()方法

#include
#include
#include
using namespace std;

int main() {
    stringstream stream;
    string b;
    stream.precision(10);  //重设置stream的精度 
    double a = 4.23233;
    stream << a;
    b = stream.str();
    cout << b << endl;
    stream.str("");   //清空缓存
    double aa = 2.3;
    stream << aa;
    b = stream.str();
    cout << b;
} 

运行结果为:

4.23233
2.3

这次stream对象的缓存被清空了。

你可能感兴趣的:(C++)