String to any data_type

mrnutty 0 Tallied Votes 330 Views Share

Convert string to other datatypes via template. See below.

#include<iostream>
#include<string>
#include<sstream>

using std::string;
using std::cout;
using std::endl;
using std::stringstream;

template<typename T>
T strTo_(const string& str)
{
	stringstream ss(str);
	T val;
	if(!(ss >> val) ) throw std::runtime_error("Invalid data type for call strTo_(const string& str)\a");
	return val;
}
int main()
{
	string str("10.20");

	cout<<"string to float : "<<strTo_<float>(str)<<endl;
	cout<<"string to int   : "<<strTo_<int>(str)<<endl;
	cout<<"string to string: "<<strTo_<string>(str)<<endl;
}