istringstream、ostringstream、stringstream 类介绍
c++的输入输出主要分为以下3种
- 标准流输入输出(基于控制I/O)
头文件:#include <iostream>
ostream:写到流中去
istream:从流中读取
iostream:对流进行读写
- 文件流输入输出(基于文件I/O)
头文件:#include <fstream>
ifstream:从文件流中读取
ofstream:写到文件流中
fstream:对文件流进行读写
- 字符流输入输出(基于字符串I/O)
头文件:#include <sstream>
istringstream:从字符串对象中读取
ostringstream:写入到字符串对象中
stringstream:对字符串对象进行读写
最近在做一道算法题目的时候,题目,遇到string对象的分割问题,故此重新学习以下stringstream便于以后查阅。stringstream主要用作string对象的分割,如下程序所示,利用stringstream分割string对象
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string str = "istringstream ostringstream stringstream";
istringstream ss(str);
string s;
while (ss >> s)
{
cout << s << endl;
}
return 0;
}
/*
输出:
istringstream
ostringstream
stringstream
*/
需要注意的是,stringstream默认以空格,换行作为截断的地方,istringstream 是不能根据你指定的分隔符来切割字符串的,但是可以利用相关的技巧实现目标截断,如下:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string str = "110 , 119 ,120";
istringstream ss(str);
int s;
char c = ',';
while (ss >> s >> c)
{
cout << s << endl;
}
return 0;
}
/*
输出:
110
119
*/
//注意不会输出120,因为后面没有,其中可以省掉标准的隔断的符号
对于字符串的特定符号分割,不建议这样做,这样做必须满足一定的条件,特定分隔符的左右必须要有空格分割,可以理解为这样,没有空格,也会把特定符号归结到字符串里面,所以必须加空格
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string str = "string,ame , fy ,";
istringstream ss(str);
string s;
char c = ',';
while (ss >> s >> c)
{
cout << s << endl;
}
return 0;
}
/*
输出:
string,ame
fy
*/