码迷,mamicode.com
首页 > 其他好文 > 详细

字符串流sstream-part2

时间:2015-05-16 18:17:13      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

    stringstream构造函数会特别消耗内存,似乎不打算主动释放内存(或许是为了提高效率),如果你要在程序中使用同一个流反复读写大量数据,将会造成大量的内部消耗,因此建议:
    1:调用clear()清除当前错误控制状态,其原型为 void clear (iostate state=goodbit);
    2:调用str("")将缓冲区清零,清除脏数据

//验证字符串流不会主动释放内存
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
    ostringstream foo("hello world");
    cout<<foo.str()<<endl;        //hello world
    cout<<foo.str()<<endl;        //hello world

    istringstream bar("hello world");
    string word;
    while(bar>>word)
        cout<<word;               //helloworld
    cout<<endl;    
    cout<<bar.str()<<endl;        //hello world

    stringstream ss;
    string str;
    while(1)
    {
        ss<<"abcdefg";
        ss>>str;
        cout<<"Size of stream = "<<ss.str().length()<<endl;        //7\n14\n21\n28...
        ss.clear();            //每次循环需要清除错误标识,因为ss>>str没有读取到数据时,会置位failbit,如果不清楚错误标识,将导致接下来的I/O无效
         system("pause");
    }
    system("pause");
    return 0;
}
//清除错误标识及清空string buffer
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
    stringstream ss("hello world");
    char ch;
    while(ss.get(ch))
        cout<<ch;                  //hello world
    cout<<endl;

    ss.clear();                    //清除ss.get()置位的failbit
    ss.str("");                    //清空string buffer
    ss<<"hello c++";    
    cout<<ss.str()<<endl;

    system("pause");
    return 0;
}

字符串流sstream-part2

标签:

原文地址:http://www.cnblogs.com/kevinq/p/4508126.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!