istringstream可以将输入的字符串转换为字符串流,可以用于分割字符串.
需要包含头文件件:#include
用法实例如下:
/*********************************************************
/ Module : app
/--------------------------------------------------------
/ FuncDescription : 演示istringstream分割字符串的方法
/ BasicKnoledge : istringstream用法
/ Blog :
*********************************************************/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
//分割空格分开的字符串
string strDevideByBlank = "aa bbb cccc";
istringstream sin(strDevideByBlank); //将str转换为istringstream(字符串流)对象
string word;
while(sin >> word) //输入字符串,遇到空格时结束
{
cout << word << "\t";
}
cout << endl;
//分开任意符号分开的字符串
string strDevideByColon = "there:is:a:lot:to:learn";
string strDevideByStar = "but*time*is*always*not*enough";
string lastWord = "test";
istringstream sin1(strDevideByColon);
//getline读取成功返回1,失败返回0
while(getline(sin1, word, ':'))
{
cout << word << "\t";
}
cout << endl;
istringstream sin2(strDevideByStar);
while(getline(sin2, word, '*'))
{
cout << word << "\t";
}
cout << endl;
return 0;
}