1

the following piece of code that I compiled on wandbox.org is causing the following error. I don't understand why I am getting the error.

// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
#include "boost/lexical_cast.hpp"

typedef unsigned  long long Ulonglong ; 

int main()
{

    Ulonglong result   = boost::lexical_cast<unsigned long long>("862.00");
    return 0;
}

Start prog.cc: In function 'int main()': prog.cc:11:15: warning: unused variable 'result' [-Wunused-variable] 11 | Ulonglong result = boost::lexical_cast("862.00"); | ^~~~~~ terminate called after throwing an instance of 'boost::wrapexcept' what(): bad lexical cast: source type value could not be interpreted as target Aborted Finish

Max Langhof
  • 23,383
  • 5
  • 39
  • 72
gringo
  • 373
  • 2
  • 4
  • 15
  • 1
    862.00 is a floating point number, not integer. – VLL Dec 18 '19 at 10:34
  • @vll so lexical_cast is different from atol? I cannot use atol because a reviewer told me it's not safe and suggested lexical_cast. we are not using C++11 neither – gringo Dec 18 '19 at 10:36
  • Your wandbox link doesn't show your snippet. – acraig5075 Dec 18 '19 at 10:38
  • 1
    My guess is that lexical_cast ensures that all the input was consumed during conversion. Which is not the case. ".00" will remain in the input buffer after conversion which causes an error. – Konstantin Stupnik Dec 18 '19 at 10:39
  • 1
    @gringo That is correct; atol ignores errors, including this one. – VLL Dec 18 '19 at 10:44

1 Answers1

3

It seems boost::lexical_cast must perform an exact conversion, with no extended behaviour. You are trying to cast a string representation of a number containing a decimal point (thus containing a fractional part) to an integer, which is not allowed.

You should either first convert to float/double (mind the data loss for very large integers) and then convert to integer, or cut off the decimal part of the string before handing it off to boost::lexical_cast.

rubenvb
  • 74,642
  • 33
  • 187
  • 332
  • FWIW, `13` is also a decimal number - a number represented in base 10. It's the decimal separator that is the problem. – Max Langhof Dec 18 '19 at 11:00