【问题标题】:how to convert std::string to boost::chrono::nanoseconds如何将 std::string 转换为 boost::chrono::nanoseconds
【发布时间】:2017-11-24 18:18:26
【问题描述】:

我已经尝试从 std::string 和 long long 进行词法转换。两者都给出零值。有什么想法吗?

boost::lexical_cast<boost::chrono::nanoseconds>(value) //value can be of std::string or long long type

【问题讨论】:

  • 你的字符串是如何格式化的?
  • 字符串包含什么?
  • 嗨,您的意见是什么?
  • @Jarod42 , @Galik , @Stefan : for long 86808525850 .same 适用于字符串,因为我使用 std::stoll() 从字符串转换为 long long
  • Edit您的问题包含所有相关信息

标签: c++ c++11 boost


【解决方案1】:

先尝试对字符串使用词法强制转换,看看会发生什么:

#include <iostream>
#include <string>
#include "boost/lexical_cast.hpp"
#include "boost/chrono.hpp"

int main()
{
    boost::chrono::nanoseconds test1{1000}; // could use long long here directly
    auto text = boost::lexical_cast<std::string>(test1);
    std::cout << text << '\n';
    auto val = boost::lexical_cast<boost::chrono::nanoseconds>(text);
    std::cout << val << '\n';
}

打印:

1000 nanoseconds
1000 nanoseconds

【讨论】:

    【解决方案2】:

    时间单位没有定义输入/输出流。

    先转换成ull:

    boost::chrono::nanoseconds(boost::lexical_cast<uint64_t>(value))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 2015-09-18
      • 2016-06-25
      • 1970-01-01
      • 2021-02-03
      相关资源
      最近更新 更多