Start New Discussion within our Software Development Community

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;
}
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.