0

like :

string num = "-0.25";

how can I convert it to a signed float?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Entel
  • 639
  • 2
  • 8
  • 12

6 Answers6

2

C++11: std::stof(num) to convert to float; also stod for double and stold for long double.

Historically: std::strtod (or std::atof if you don't need to check for errors); or string streams.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

strtod() is a good bet for C.

I have no idea if C++ has other bets.

pmg
  • 106,608
  • 13
  • 126
  • 198
1

The std::stof function should work fine.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

You can use istringstream:

std::string num = "-0.25";

std::istringstream iss ( num);

float f_val = 0;

iss >> f_val;
4pie0
  • 29,204
  • 9
  • 82
  • 118
0

You can use the atof function. http://www.cplusplus.com/reference/cstdlib/atof/

For C++ you can also use std::stof http://www.cplusplus.com/reference/string/stof/

edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47
  • `atof()` isn't really idiomatic *C++*, and even in *C* isn't usually recommended because it lacks any facility for error-handling. – Emmet Mar 14 '14 at 16:28
  • @Emmet - the question was 'how to convert' and my answer will do the trick. Boo on you for downvote. – edtheprogrammerguy Mar 14 '14 at 16:29
  • 1
    The downvote was when your answer just mentioned `atof()`. What should we do when someone makes a recommendation that might work, but is the worst available option? – Emmet Mar 14 '14 at 16:36
0

You can convert the string to a signed float by using the function atof. Like :

float myValue = (float)atof("0.75");

Note that you should also checked if the passed value is a valid numerical value otherwise the behaviour could be unpredictable.

There is also an other solution :

    string mystr ("1204");
    int myint;
    stringstream(mystr) >> myint;
Spiralwise
  • 338
  • 3
  • 18