在某些题目需要处理字符串时,这些题目往往是输入的一行中包含多个字符以及空格,这个时候就可以利用 stringstream进行单个字符或者单个字符串分析处理了
1.头文件:#include
2.stringstream是C++提供的串流(stream)物件。
3.stringstream的作用就是从string对象读取字符或字符串。
例:
string s = "ABCD";
stringstream ss(s);
char ch;
while(ss>>ch){
cout << ch << " ";
}
//运行结果
//A B C D
又如:
string s = "hello world";
stringstream ss(s);
string str;
while(ss>>str){
cout << str << " ";
}
//运行结果
//hello world
其中:
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;
}