c++boostlexical-castboost-lexicalcast

boost bad lexical cast: source type value could not be interpreted as target when converting a string to unsigned long long


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


Solution

  • 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.