簡體   English   中英

Lexical_cast引發異常

[英]Lexical_cast throws exception

在將字符串轉換為int8_t的過程中boost :: lexical_cast引發異常,但是int32_t-規范。

int8_t有什么問題?

#include <iostream>
#include <cstdlib>
#include <boost/lexical_cast.hpp>

int main()
{
    try
    {
        const auto a = boost::lexical_cast<int8_t>("22");
        std::cout << a << std::endl;
    }
    catch( std::exception &e )
    {
        std::cout << "e=" << e.what() << std::endl;
    }
}

對於boost::lexical_cast ,假定底層流的字符類型為char,除非Source或Target要求寬字符流傳輸,在這種情況下,底層流使用wchar_t。 以下類型也可以使用char16_t或char32_t進行寬字符流傳輸

促進詞法轉換

因此,在執行以下代碼更改之后:

#include <iostream>
#include <cstdlib>
#include <boost/lexical_cast.hpp>

int main() 
{
   try
   {
       const auto a = boost::lexical_cast<int8_t>("2");
       const auto b = boost::lexical_cast<int16_t>("22");
       std::cout << a << " and "<< b << std::endl;
   }
   catch( std::exception &e )
   {
      std::cout << "e=" << e.what() << std::endl;
   }
 return 0;
}

給出以下輸出

2和22

因此,我覺得每個字符都被當作char

因此,對於const auto a = boost::lexical_cast<int16_t>("2"); 2被視為需要int8_t的單個char

並且,對於const auto b = boost::lexical_cast<int16_t>("22"); 將22作為需要int16_t的兩個char值。

希望對您有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM