I have following situation: I'm writing two programs, the first one starts with windows and writes the current system time in a text document. The code for this looks like this:
auto start = std::chrono::system_clock::now();
std::time_t start_time = std::chrono::system_clock::to_time_t(start);
ofstream Write ("Time.txt");
Write << std::ctime(&start_time);
The date format looks like this: Thu Jul 16 14:19:53 2020.
My second program autostarts with the shutdown. It should build the difference between the current system time and the starting time and write the difference in a different text document.
#include <iostream>
#include <ctime>
#include <string>
#include <cmath>
#include <fstream>
#include <chrono>
#include <windows.h>
using namespace std;
double k; //Get leftover time from txt doc//
int s; //Seconds//
int m; //Minutes//
int h; //Hours//
int d; //Days//
long int z; //Var containing new leftover time//
int main()
{
ifstream Time ("Time.txt");
Time >> start;
//Get starting time//
ifstream Check ("Test.txt");
Check >> d; //Reading days from txt doc to d//
Check >> h; //Reading hours from txt doc to h//
Check >> m; //Reading minutes from txt doc to m//
Check >> s; //Reading seconds from txt doc to s//
k = (s + 60*m + 3600*h + 24*3600*d);
auto end = std::chrono::system_clock::now();
//Get current time ending the program//
std::chrono::duration<double> elapsed_seconds = end-start;
//Calculate difference between start and end//
z = (k-round(elapsed_seconds.count()));
//Calculate time difference in seconds//
//Converting seconds into days, hours, minutes, seconds//
d = z / (24*3600);
h = (z / 3600) % 24;
m = (z / 60) % 60;
s = z % 60;
//End of converting//
ofstream Write ("Test.txt");
Write << d << "\n" << h << "\n" << m << "\n" << s;
//Write all values back to txt doc//
}
The problem I have is that I don't have an idea on how to get the starting time from the Time.txt in a format I can use in this chrono operation std::chrono::duration<double> elapsed_seconds = end-start
.
I've tried to set it up like in the startup program
std::time_t start_time = std::chrono::system_clock::to_time_t(start);
ifstream Time ("Time.txt");
Time >> start;
The result: a ridiculous negative number in the Test.txt which is obviously wrong considering I didn't mess with the system time.
A string variable didn't help me much either. It gets the job done copying the txt line to the string variable but afterwards I didn't manage to transform it into the right chrono variable.
I hope someone has an idea on how to do this. I'm thanking you already for your answers.