Convert string to float in C ++
What is the best way to convert a string to float (in C ++) considering the string might not be valid. Here is the input type
20.1
0.07
x
0
I used strtof , which works well enough, but the problem is that it returns 0 both on error and when the string "0" is passed to the function.
The code I am using is pretty simple
float converted_value = strtof(str_val.c_str(), NULL);
if (converted_value == 0) {
return error;
}
Is there a way to fix this code so that I can distinguish between line 0 and error 0? what are the disadvantages if i use scanf?
source to share
C ++ 11 has functions that do this now, in your case std::stof
Note that in regards to handling your validation, it will throw an exception std::invalid_argument
if the argument cannot be converted.
For completeness, there are more functions like this here.
std::stoi // string to int
std::stol // string to long
std::stoll // string to long long
std::stof // string to float
std::stod // string to double
std::stold // string to long double
source to share