为了使用流操作从一个字符串中读取数据,需要创建istringstream对象,下面的例子说明了如何使用istringsstream对象:
#include <cassert>
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
istringstream strStream("1000 3.14 Hello world");//create an input string stream using a string
int i;
double f;
strStream >> i >> f;//get a int and a float
assert(i = 1000);
double relErr = (fabs(f) - 3.14)/3.14;
assert(relErr <= numeric_limits<double>::epsilon();
string str;
strStream >> str;//get a string with first word
assert(str == "Hello");
cout << strStream.rdbuf();//print " world"
}
使用istringstream读取字符串数据
本文介绍了如何利用C++标准库中的istringstream类从字符串中读取整数、浮点数和字符串。通过创建istringstream对象并使用流操作符,可以方便地解析字符串中的不同数据类型。
1551

被折叠的 条评论
为什么被折叠?



