stringstream()
#include<sstream>
stringstream可以使string与各种内置类型数据之间的转换
直接用getline()
当我们直接利用getline(),自定义字符,从cin流中分割字符,例如
输入 “one#two”
string str;
ss << str2;
while (getline(cin, str, '#'))
cout << str<< endl;
system("pause");
return 0;
输出结果为
one
后面的 two并没有输出
使用stringstream
此时如果我们是用 stringstream 流,例如:
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main(){
string str;
string str_cin("one#two#three");
stringstream ss;
ss << str_cin;
while (getline(ss, str, '#'))
cout << str<< endl;
system("pause");
return 0;
}
结果:
one
two
three
使用数组
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main(){
int j=0;
string str, result[3];
string str_cin("one#two#three");
stringstream ss;
ss << str_cin;
//赋值
while (getline(ss, str, '#')){
result[j] = str;
j++;
}
//遍历
for(int i=0; i<3; i++){
cout<<result[i]<<endl;
}
system("pause");
return 0;
}
使用迭代器
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
int main(){
string str;
vector<string> result;
string str_cin("one#two#three");
stringstream ss;
ss << str_cin;
//赋值
while (getline(ss, str, '#')){
result.push_back(str);
}
cout<<"迭代器遍历:"<<endl;
//定义一个迭代器
vector<string>::iterator iter;
for(iter = result.begin(); iter != result.end(); iter++){
cout<<*iter<<endl;
}
system("pause");
return 0;
}
数组&迭代器结果:
one
two
three
二次迭代
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
int main(){
string str;
vector<string> result;
string str_cin("one#two#three");
stringstream ss;
ss << str_cin;
//赋值
while (getline(ss, str, '#')){
result.push_back(str);
}
cout<<"迭代器遍历:"<<endl;
//定义一个迭代器
vector<string>::iterator iter;
for(iter = result.begin(); iter != result.end(); iter++){
for(vector<string>::size_type sty=0; sty!=(*iter).size(); ++sty){
cout<<(*iter)[sty]<<endl;//cout<<iter1[sty]<<endl;//应先通过迭代器寻址再使用[]算符
}
}
system("pause");
return 0;
}
二次迭代得到的结果为:
o
n
e
t
w
o
t
h
r
e
e
再或者:
int main(){
string str="nice to meet you";
stringstream stream(str);
string s;
while(stream>>s){
cout<<s<<endl;
}
return 0;
}
输出:
nice
to
meet
you