C/C++文件读写详解(二)(istringstream、ostringstream、stringstream)

1.#include <sstream>

istringstream类

描述:从流中提取数据,支持 >> 操作

字符串可以包括多个单词,单词之间使用空格分开
istringstream的构造函数原形:  

istringstream::istringstream(string str);  

#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;

void main()
{
	string strFilePath = "test.txt";

	ifstream infile;
	infile.open(strFilePath.c_str());

	string strLine, strSplit;

	istringstream ss;
	while (getline(infile,strLine))//加载文本中一行字符串
	{
		ss.str(strLine);		   //将strLine中的字符串存入字符串流中
		string strr = ss.str();    //可以通过str()将字符流转换为字符串
		cout << strr << endl;
		while (ss >> strSplit)     //以空格为界,分离字符串
		{
			cout << strSplit << endl;
		}
	}
}

2.ostringstream类

把其他类型的数据写入流(往流中写入数据),支持<<操作

ostringstream的构造函数原形:  

ostringstream::ostringstream(string str);  

#include <fstream>
#include <iostream>
#include <sstream>

using namespace std;

void main()
{
	ostringstream ostr("abd cd");
	cout << ostr.str() << endl;

	ostr.put('5');
	cout << ostr.str() << endl;

	ostr.put('4');
	cout << ostr.str() << endl;


	ostr.put('x');//put()对单个字符有效,若出现多个,以最后一个位准
	cout << ostr.str() << endl;

	ostr << "1234444";
	string str3 = ostr.str();
	cout << str3 << endl;
}


3.stringstream类

是对istringstream和ostringstream类的综合,支持<<, >>操作符,可以进行字符串到其它类型的快速转换

*将基本数据类型变为字符类型

#include <fstream>
#include <iostream>
#include <sstream>

using namespace std;


void main()
{
	/*整型变字符串*/
	int n = 10;
	string sstr;
	stringstream stream;
	stream << n;
	stream >> sstr;
	cout << sstr << endl;

	//多次使用stringstream,要先清空下,不能使用stream.str("");否则下面输出10   
	stream.clear();
	//stream.str("");

	/*char* 变 string*/
	char cStr[10] = "hello";
	stream << cStr;
	stream >> sstr;
	cout << sstr << endl;
}

*将字符串变为基本数据类型

#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;


void main()
{
	stringstream stream;
	/*字符串 变 double*/
	double dn;
	string strd = "11.11";

	stream << strd;
	stream >> dn;
	cout << dn << endl;
	//多次使用stringstream,要先清空下,不能使用stream.str("");   
	stream.clear();

	/*string 变 char* */
	string strc = "hello";
	char cStrr[10];
	stream << strc;
	stream >> cStrr;
	cout << cStrr << endl;
}

由于stringstream构造函数会特别消耗内存,如果你要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消耗,因些这时候,需要适时地清除一下缓冲 (用 stream.str("") )。

参考

1.https://blog.csdn.net/bruce_0712/article/details/72892244

欢迎指正,转载请说明出处

猜你喜欢

转载自blog.csdn.net/qq_42189368/article/details/80621576
今日推荐