天天看點

C++ stringstream的使用 類型轉換以及字元分離(功能類似split)

參考:

http://www.cppblog.com/Sandywin/archive/2007/07/13/27984.html

###################################################

//
//ostringstream, istringstream, stringstream使用
//各種基礎類型轉換
//
/

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


//模版,用于stingstream和int/float/double等類型的轉換
template<class out_type,class in_value>
out_type convert(const in_value & t)
{
	stringstream stream;
	
	stream<<t;//向流中傳值
	out_type result;//這裡存儲轉換結果
	stream>>result;//向result中寫入值

	return result;
}

int main(int argc, char* argv[])
{
	//int轉string
	int temp1_num=100;
	string temp1_str=convert<string>(temp1_num);
	cout<<temp1_str<<endl;

	//string轉int
	string temp2_str="121";
	int temp2_int=convert<int>(temp2_str);
	cout<<temp2_int<<endl;

	//float(double)轉string
	float temp3_num=100.32;
	string temp3_str=convert<string>(temp3_num);
	cout<<temp3_str<<endl;

	//string轉float(double)
	string temp4_str="322.11";
	float temp4_num=convert<float>(temp4_str);
	cout<<temp4_num<<endl;

	//stringstream用于split很友善
	string a, b, c, d;
	string lines="adfa;asdfasd;fasdf;ccc";
	stringstream line(lines);
	getline(line, a, 'f');
	getline(line, b, ';');
	getline(line, c, ';');
	getline(line, d);
	cout<<"a = "<<a<<endl;
	cout<<"b = "<<b<<endl;
	cout<<"c = "<<c<<endl;
	cout<<"d = "<<d<<endl;

	cin.get();
	return 0;
}
           
C++ stringstream的使用 類型轉換以及字元分離(功能類似split)

繼續閱讀