You can use stringstreams to convert the string to the data type you want:
#include <sstream>
#include <string>
#include <iostream>
int main() {
std::string num_str = "10.5";
std::istringstream iss(num_str);
float f_val = 0;
iss >> f_val;
//this will output 10.5 (as expected)
std::cout << f_val << std::endl;
return 0;
}
Which will assign f_val
to the value of the string.
This approach is preferred in that it has built-in checking of conversion, and it can work on any of the fundamental C++ types. Hence, if you can can create a template function to perform the checking for you and return that particular value of the type you desire:
#include <sstream>
#include <iostream>
#include <string>
#include <stdexcept>
template<typename T>
T ConvertStringToNumber(const std::string& str)
{
std::istringstream ss(str);
T number = 0;
ss >> number;
if (ss.fail( ))
{
throw std::invalid_argument("ConvertStringToNumber:" + str);
}
return number;
}
int main(int argc, char argv[]){
std::string num_str = "10.5";
float f = ConvertStringToNumber<float>(num_str);
std::cout << f << std::endl;
return 0;
}