user2449761
user2449761

Reputation: 1229

How to add duration to time_point?

I tried something like this:

using clock = std::chrono::system_clock;
clock::time_point nowp = clock::now();
clock::time_point end = nowp + std::chrono::seconds(10);
time_t nowt =  clock::to_time_t ( nowp );
time_t endt =  clock::to_time_t ( end);
std::cerr  << " " << ctime(&nowt) << " " << ctime(&endt) << std::endl;

But it prints:

Sat Dec 16 15:06:43 2017
Sat Dec 16 15:06:43 2017

What am I doing wrong here? How do add ten seconds to now?

Upvotes: 3

Views: 7972

Answers (1)

RiaD
RiaD

Reputation: 47658

The problem might be because ctime store result in some static storage and just returns the pointer to you.

So it overwrites one result with another one and prints it 2 times. Order of operation is not fixed by the standard so what it does:

  1. Call ctime with one argument, which saves representation in internal buffer and returns pointer to it.
  2. Call ctime with another argument, which saves representation in the same internal buffer and returns pointer to it.
  3. Prints value from both char*'s (actually the same pointer)

Solution is to force order of evaluation by dividing operations with ;

Code that fixes problem for me

#include <iostream>
#include <chrono>
using namespace std;


int main() {
    using clock = std::chrono::system_clock;
    clock::time_point nowp = clock::now();
    clock::time_point end = nowp + std::chrono::seconds(10);
    time_t nowt =  clock::to_time_t ( nowp );
    time_t endt =  clock::to_time_t ( end);
    std::cout  << " " << ctime(&nowt) << "\n";
    std::cout << ctime(&endt) << std::endl;
    return 0;
}

Upvotes: 5

Related Questions