Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting string to float in c++

What is the best way to convert a string to float(in c++), given that the string may be invalid. Here are the type of input

20.1

0.07

x

0

I used strtof which works quite well but the issue is it returns 0 both on error as well as when string "0" is passed into 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 any way I could fix this code so I can differentiate between string 0 and error 0? what are the disadvantages if I use scanf?

like image 788
codebreaker Avatar asked Dec 20 '22 07:12

codebreaker


1 Answers

C++11 actually has functions that do this now, in your case std::stof

Note that as far as handling your validation, it will throw an std::invalid_argument exception if the argument cannot be converted.

For completeness, here are more of such functions

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
like image 74
Cory Kramer Avatar answered Jan 05 '23 16:01

Cory Kramer