helix
helix

Reputation: 1056

how to convert std::string to boost::chrono::nanoseconds

I have tried lexical casting it from std::string and from long long. both gives zero value. any ideas?

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

Upvotes: 0

Views: 441

Answers (2)

wally
wally

Reputation: 11002

Try using lexical cast to a string first to see what is expected:

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

Prints:

1000 nanoseconds
1000 nanoseconds

Upvotes: 2

sehe
sehe

Reputation: 392893

The time units do not have input/output streaming defined.

Just convert to ull first:

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

Upvotes: 1

Related Questions