简体   繁体   English

如何使用boost词法转换将字符串转换为unsigned short?

[英]how to convert string to unsigned short using boost lexical cast?

I have a string containing the port, when I try to create a tcp endpoint I need its value in unsigned short 我有一个包含端口的字符串,当我尝试创建tcp端点时,我需要使用unsigned short的值

  std::string to_port;
    ....
    boost::lexical_cast<unsigned short>(to_port));

throws an exception bad lexical cast: source type value could not be interpreted as target 引发异常bad lexical cast: source type value could not be interpreted as target

The following program works correctly: 以下程序可以正常运行:

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

int main(int argc, const char *argv[])
{
    std::string to_port("8004");
    unsigned short intport = boost::lexical_cast<unsigned short>(to_port);

    std::cout << intport << std::endl;
    std::cout << std::hex << intport << std::endl;
    return 0;
}

But if we modify the first line of main into: 但是,如果我们将main的第一行修改为:

std::string to_port;

We get the exception: 我们得到一个例外:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'
  what():  bad lexical cast: source type value could not be interpreted as target
Aborted (core dumped)

Which leads to the conclusion that there's something wrong with the parameter you are passing to the lexical_cast . 得出的结论是,您传递给lexical_cast的参数有问题。

Can you print the to_port variable to verify its content just before the lexical_cast ? 您可以在lexical_cast之前打印to_port变量以验证其内容吗? Are you sure it is properly initialized and still in-scope when used (eg, no temporaries involved, no dangling pointers)? 您确定它已正确初始化并且在使用时仍在作用域内(例如,不涉及临时对象,不悬挂指针)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM