istringstream类用于执行C++风格的字符串流的输入操作。
具体分析
istringstream类
描述:从流中提取数据,支持 >> 操作
这里字符串可以包括多个单词,单词之间使用空格分开
istringstream的构造函数原形:
istringstream::istringstream(string str);
初始化:使用字符串进行初始化
istringstream istr("1 56.7");
istr.str("1 56.7");//把字符串"1 56.7"存入字符串流中
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
istringstream istr("1 56.7");
cout<<istr.str()<<endl;//直接输出字符串的数据 "1 56.7"
string str = istr.str();//函数str()返回一个字符串
cout<<str<<endl;
int n;
double d;
//以空格为界,把istringstream中数据取出,应进行类型转换
istr>>n;//第一个数为整型数据,输出1
istr>>d;//第二个数位浮点数,输出56.7
//假设换下存储类型
istr>>d;//istringstream第一个数要自动变成浮点型,输出仍为1
istr>>n;//istringstream第二个数要自动变成整型,有数字的阶段,输出为56
//测试输出
cout<<d<<endl;
cout<<n<<endl;
system("pause");
return 1;
}
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main()
{
string a = "jb b jlha lag lajsi";
istringstream in(a);
string s;
while (in >> s)
{
cout << s << endl;
}
system("pause");
return 0;
}