【问题标题】:how to convert string to unsigned short using boost lexical cast?如何使用 boost lexical_cast 将字符串转换为无符号短字符串?
【发布时间】:2013-05-25 15:41:54
【问题描述】:

我有一个包含端口的字符串,当我尝试创建一个 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

【问题讨论】:

  • 它对我有用。 to_port 包含什么?
  • 例如“8004”或任何端口号
  • this example 不适合你吗?
  • 请向我们发送演示问题的完整(但最小)程序
  • 可能想在lexical_cast&lt;&gt; 的行上插入一个断点并验证to_port 的内容是否正确。

标签: c++ boost lexical-cast


【解决方案1】:

以下程序正常运行:

#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 之前验证其内容? 您确定它已正确初始化并且在使用时仍在范围内(例如,不涉及临时对象、没有悬空指针)?

【讨论】:

    猜你喜欢
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    相关资源
    最近更新 更多