C++98中std::istringstream的构造函数是
explicit istringstream (const string& str,
ios_base::openmode which = ios_base::in);
(默认构造函数,已经其他构造函数这里省略,只列举经常用到的构造函数)
cplusplus上的文档
第一个参数是const string& str
可以通过const string& str对istringstream进行初始化。
用法举例:
// istringstream::str
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::istringstream
int main () {
std::istringstream iss;
std::string strvalues = "32 240 2 1450";
iss.str (strvalues);
for (int n=0; n<4; n++)
{
int val;
iss >> val;
std::cout << val << '\n';
}
std::cout << "Finished writing the numbers in: ";
std::cout << iss.str() << '\n';
return 0;
}
运行结果:
32
240
2
1450
Finished writing the numbers in: 32 240 2 1450
唯一要注意的是for循环的次数,如果n<4改成n<8时,会发生什么?
运行结果:
32
240
2
1450
1450
1450
1450
1450
Finished writing the numbers in: 32 240 2 1450
这篇文章就是记录的这个循环次数超出的问题:
而采用while循环,则避免了计算循环次数的问题。
举例:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
istringstream is("I am\tlove C++\nand I love C");
string str;
//默认是空格或者回车符或者tab,会输出如下内容:I am love C++ and I love C
while (is >> str) {
cout << str << endl;
}
getchar();
return 0;
}
运行结果:
I
am
love
C++
and
I
love
C
问题描述:
假如有一行用空格隔开的字符串的话,如何提取出每一个字符串
比如输入
abc def ghi
然后我们又需要存下来每一个字符串的话,需要怎么做。
可以采用std::istringstream实现这个功能。
可以看这里:C++ istringstream总结