Convert string to other datatypes via template. See below.
String to any data_type
#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;
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.