![](/img/trans.png)
[英]how to convert string to unsigned short using boost lexical cast?
[英]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;
}
啟動 prog.cc:在函數 'int main()' 中:prog.cc:11:15: 警告:未使用的變量 'result' [-Wunused-variable] 11 | Ulonglong result = boost::lexical_cast("862.00"); | ^~~~~~ 拋出“boost::wrapexcept”what() 實例后調用終止:詞法轉換錯誤:源類型值無法解釋為目標中止完成
似乎boost::lexical_cast
必須執行精確轉換,沒有擴展行為。 您試圖將包含小數點(因此包含小數部分)的數字的字符串表示形式轉換為整數,這是不允許的。
您應該首先轉換為 float/double(注意非常大整數的數據丟失),然后轉換為整數,或者在將其交給boost::lexical_cast
之前切斷字符串的小數部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.