6

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?

codebreaker
  • 81
  • 1
  • 1
  • 5
  • you can try [boost::lexical_cast](http://www.boost.org/doc/libs/1_57_0/doc/html/boost_lexical_cast.html) – tumdum Jan 12 '15 at 16:11
  • 4
    Why do people always suggest bloating their executable with boost for something as simple as this? It's understandable for projects that might benefit from widespread use of multiple boost features, but to compile/link against such an enormous library just so OP can convert a string to float is simply awful advice. – Julian Jan 12 '15 at 16:55

3 Answers3

7

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
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
6

You do it by not ignoring the second parameter - it will tell you where the scanning stopped. If it's the end of the string then there wasn't an error.

char *ending;
float converted_value = strtof(str_val.c_str(), &ending);
if (*ending != 0) // error
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • 3
    This is the only answer that actually answers what was asked in the question. All of the others just mention _"Use this or that alternative"_ but don't actually explain what has been asked for. – πάντα ῥεῖ Jan 12 '15 at 16:43
0

Do neither and use stringstream.

std::stringstream s(str_val);

float f;
if (s >> f) {
    // conversion ok
} else {
    // conversion not ok
}
Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135