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?

+3


source to share


3 answers


You do this without ignoring the second parameter - it will tell you where the scan stopped. If this is the end of the line, then there was no error.



char *ending;
float converted_value = strtof(str_val.c_str(), &ending);
if (*ending != 0) // error

      

+4


source


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

      

+4


source


Do not use or use stringstream

.

std::stringstream s(str_val);

float f;
if (s >> f) {
    // conversion ok
} else {
    // conversion not ok
}

      

0


source







All Articles