stringstream用法

1.头文件:#include<sstream>

2.stringstream是C++提供的串流(stream)物件,其中:

clear()重置流的标志状态;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;
    
    stream<<"90";
    stream>>b;
    
    cout<<a<<endl;
    cout<<b<<endl;

    system("PAUSE ");
    return  EXIT_SUCCESS;
} 

运行结果:

 预期b为90,但是出现-858993460,这是由于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.clear();
    
    stream<<"90";
    stream>>b;
    
    cout<<a<<endl;
    cout<<b<<endl;

    system("PAUSE ");
    return  EXIT_SUCCESS;
} 

运行结果:

 但是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,每次都增加占用的内存。

 可以利用stringstream.str("")来清空stringstream。

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.

#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;
} 

运行结果:

 stringstream默认空格会直接分词!

題目:输入的第一行有一个数字 N 代表接下來有 N 行数字,每一行数字里有不固定个数的整数,打印每一行的总和。

输入:

3
1 2 3
20 17 23 54 77 60
111 222 333 444 555 666 777 888 999

输出:

6
251
4995

string s;
stringstream ss;
int n, i, sum, a;
cin >> n;
getline(cin, s); // 换行读取
for (i=0; i<n; i++)
{
getline(cin, s);
ss.clear();
ss.str(s);
sum=0;
while (1)
{
ss >> a;
if ( ss.fail() )
break; sum+=a; } cout << sum << endl; }
原文地址:https://www.cnblogs.com/hhhhan1025/p/11521273.html