提升错误的词法转换:将字符串转换为 unsigned long long 时,源类型值无法解释为目标

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

我在 wandbox.org 上编译的以下代码导致了以下错误。我不明白为什么会收到错误消息。

// 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

似乎 boost::lexical_cast 必须执行精确转换,没有扩展行为。您试图将包含小数点(因此包含小数部分)的数字的字符串表示形式转换为整数,这是不允许的。

您应该首先转换为 float/double(注意非常大的整数的数据丢失)然后转换为整数,或者在将其传递给 [=10= 之前切断字符串的小数部分].