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

时间:2013-05-25 15:41:55

标签: c++ boost lexical-cast

我有一个包含端口的字符串,当我尝试创建一个tcp端点时,我需要在unsigned short中使用它的值

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

抛出异常bad lexical cast: source type value could not be interpreted as target

1 个答案:

答案 0 :(得分:5)

以下程序正常运行:

#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;
}

但是如果我们将main的第一行修改为:

std::string to_port;

我们得到例外:

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)

这导致得出的结论是您传递给lexical_cast的参数有问题。

您可以打印to_port变量以在lexical_cast之前验证其内容吗? 你确定它被正确初始化并且在使用时仍然在范围内(例如,没有涉及临时指示,没有悬空指针)?

相关问题