0

like :

string num = "-0.25";

how can I convert it to a signed float?

Yu Hao
  • 115,525
  • 42
  • 225
  • 281
Entel
  • 599
  • 2
  • 7
  • 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
  • 242,813
  • 27
  • 432
  • 630
1

strtod() is a good bet for C.

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

pmg
  • 103,426
  • 11
  • 122
  • 196
1

The std::stof function should work fine.

Some programmer dude
  • 380,411
  • 33
  • 383
  • 585
1

You can use istringstream:

std::string num = "-0.25";

std::istringstream iss ( num);

float f_val = 0;

iss >> f_val;
4pie0
  • 28,488
  • 8
  • 76
  • 116
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,880
  • 5
  • 27
  • 45
  • `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
  • 15