-1

What would this return?

boost::lexical_cast<float>("-2"); 

I am not able to find a lexical_cast conversion from string to float example in the documentation.

Thanks

theDarkerHorse
  • 109
  • 1
  • 1
  • 15
  • 5
    did u try running it and printing the value? – Bill Jun 04 '13 at 00:50
  • I am building my environment just as I posted this question.It would take a couple of hours for my boost environmnet to get set up. I thought I could get a quick answer from someone who already has it set up. – theDarkerHorse Jun 04 '13 at 00:54
  • @highriser JFYI, since you mentioned building Boost: although have to build a few parts of Boost, lexical_cast is one of the very large majority of parts of Boost that is completely implemented as header files. – wjl Jun 04 '13 at 01:17
  • @highriser Searching Google for "stackoverflow boost lexical_cast float" brought up this question: http://stackoverflow.com/questions/1012571/stdstring-to-float-or-double. The answers by stefanB and sharth are exactly what you are looking for. – jogojapan Jun 04 '13 at 02:06

1 Answers1

2

This:

float value = boost::lexical_cast<float>("-2"); 

Is basically equivalent to this:

float value;
{
  std::stringstream ss;
  ss << "-2";
  ss >> value;
}

Of course, Boost's lexical_cast does a few other things behind the scenes, and handles errors with exceptions rather than iostream error states, but for the most part, if a conversion through a std::stringstring will work, boost::lexical_cast will work the same way.

The value of the float is, of course, -2.0f.

wjl
  • 7,519
  • 2
  • 32
  • 41
  • I found this in the QA section. Does this apply in this case too? Question:Why std::cout << boost::lexical_cast("-1"); does not throw, but outputs 4294967295? Answer: boost::lexical_cast has the behavior of stringstream, which uses num_get functions of std::locale to convert numbers. If we look at the [22.2.2.1.2] of Programming languages — C++, we'll see, that num_get uses the rules of scanf for conversions. And in the C99 standard for unsigned input value minus sign is optional, so if a negative number is read, no errors will arise and the result will be the two's complement. – theDarkerHorse Jun 04 '13 at 01:16
  • http://www.boost.org/doc/libs/1_47_0/libs/conversion/lexical_cast.htm – theDarkerHorse Jun 04 '13 at 01:16
  • 3
    @highriser No. The problem you've quoted above is for lexically converting a negative number into an unsigned type. `float` is not unsigned so that entire discussion is irrelevant. =) – wjl Jun 04 '13 at 01:32