I am making a program in C++ and I wish to print the time at the start and end of the program execution. I have used the following code in main() to output the timestamp at the begining but the values do not update for the end of the program.
I am currently just working procedurally but I am thinking maybe a function would benefit me here.
int main(int argc, char **argv) {
time_t now;
struct tm *current;
now = time(0);
current = localtime(&now);
cout <<"Examination began at: " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec << endl;
//program execution....
cout <<"Examination ended at: " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec << endl;
cout << "PROGRAM END++++++++++++++++++++++++++++++++++" << endl;
return 0;
}
I understand from running the program that it is just using the same values the second time round, how would I go about making this a function?
The value of the 'current' time function is only set with a call to localtime(). The reason you're seeing the same value at the beginning and end of the program is because you've only called that function once. Reset the value of 'now' to time(0), and
'current' to the value of localtime(&now) after program execution, and you'll see the desired update.
To get the time at exit, you just need to repeat the calls to time and localtime.
int main(int argc, char **argv) {
time_t now;
struct tm *current;
now = time(0);
current = localtime(&now);
cout <<"Examination began at: " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec << endl;
//program execution....
now = time(0);
current = localtime(&now);
cout <<"Examination ended at: " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec << endl;
cout << "PROGRAM END++++++++++++++++++++++++++++++++++" << endl;
return 0;
}
You asked about making this a function. I'm not sure that you need to, but if you want to, it might look like this:
void write_timestamp(std::ostream& o, const char *when) {
time_t now;
struct tm *current;
now = time(0);
current = localtime(&now);
o << when << ": " << current->tm_hour <<":" << current->tm_min <<":" << current->tm_sec << endl;
}
int main(int argc, char **argv) {
write_timestamp(cout, "Examination began at");
//program execution....
write_timestamp(cout, "Examination ended at");
cout << "PROGRAM END++++++++++++++++++++++++++++++++++" << endl;
return 0;
}
localtime only has a one-second resolution, so as #littleadv points out, you would get more accurate results using clock, getrusage, or times. Or, since you're using C++, you might find Boost.Timer useful.
You can get better results by using functions like clock, getrusage or times. Read about these functions here.
Related
I've been working on a simple console application and was stopped when, upon compiling my latest code, it began outputting strings of text and integers which did not match what I have entered.
The purpose of the program thus far is simple: to input a string of data and for it to output correctly multiple times in the console application. Below I have linked the pseudocode.
Thanks in advance.
#include <iostream>
#include <string>
void printIntro();
void RunApp();
bool RequestRestart();
std::string GetAttempt();
int main() // entry point of the application
{
printIntro();
RunApp();
RequestRestart();
return 0;
}
void printIntro() {
// introduce the program
constexpr int WORD_LENGTH = 8; // constant expression
std::cout << "Welcome to the Bull and Cow guessing game\n";
std::cout << "Can you guess the " << WORD_LENGTH;
std::cout << " letter isogram I am thinking of?\n\n";
return;
}
void RunApp()
{
// loop for number of attempts
constexpr int ATTEMPTS = 5;
for (int count = 1; count <= ATTEMPTS; count++)
{
std::string Attempt = GetAttempt();
std::cout << "You have entered " << GetAttempt << "\n";
std::cout << std::endl;
}
}
std::string GetAttempt()
{
// receive input by player
std::cout << "Enter your guess: \n";
std::string InputAttempt = "";
std::getline(std::cin, InputAttempt);
return InputAttempt;
}
bool RequestRestart()
{
std::cout << "Would you like to play again?\n";
std::string Response = "";
std::getline(std::cin, Response);
std::cout << "Is it y?: \n" << (Response[0] == 'y'); //response must be in brackets
return false;
}
You have to change this line
std::cout << "You have entered " << GetAttempt << "\n";
instd::cout << "You have entered " << Attempt << "\n";
In this way you do not print the address of the function, just like you did before, but the variable in which you stored the return value of the GetAttempt function.
You are printing a pointer to GetAttempt. Instead print Attempt:-
std::cout << "You have entered " << Attempt << "\n";
I have a method FormatOutPut() that internally calls a "callBack" method MyFunct() in C++. There is a crash, when the control comes out the FormatOutPut(). The callback method MyFunct() just prints the output on the screen. When I debugged the code using windbg I got the following traces,
(1250.1270): Stack buffer overflow - code c0000409 (!!! second chance !!!)
What I am guessing is that,the return address on the stack for the FormatOutPut(), is corrupted by the callback method. So when control is shifted back to the calling method it crashes.
When I comment out the callback method everything works fine. Any inputs on this will be great help.
Callback method prototype is as below,
typedef void(__stdcall *MyCallBack)(char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,int, int );
Body:-
void MyCallbackRoutine(char* GetFeature,char* GetVersion,char* GetStartDate, char* GetExpireDate, char* GetUsers,char* GetKey,char* GetVendorString, char* GetHostID,char* GetErrorMsg,char* GetLicense,int GetCheckOutStatus, int nCount)
{
if ( nCount == 0 )
{
_strtime_s( timeCallbackstart, 10 );
time(&startCallbackstart);
bOnlyOnce = true;
}
cout << endl;
cout << "-------------------------------------------------------" << endl;
cout << "GetCheckOutStatus: " << GetCheckOutStatus << endl;
cout << "GetErrorMsg: " << GetErrorMsg << endl;
cout << endl;
cout << "GetFeature: " << GetFeature << endl;
cout << "GetVersion: " << GetVersion << endl;
cout << "GetStartDate: " << GetStartDate << endl;
cout << "GetExpireDate: " << GetExpireDate << endl;
cout << "GetUsers: " << GetUsers << endl;
cout << "GetKey: " << GetKey << endl;
cout << "GetVendorString: " << GetVendorString << endl;
cout << "GetHostID: " << GetHostID << endl;
cout << "GetLicense: " << GetLicense << endl;
cout << endl;
cout << "Licenscounter: " << nCount << endl;
cout << "------------------------------------------------------" << endl;
cout << endl;
}
Thanks and Regards,
AKJ
The issue that I see is that your calling convention of __stdcall for the typedef of the function prototype and the callback function itself does not match. If the calling convention does not match up, stack issues can arise when returning from the called function.
More on calling conventions here.
The typedef for the function is as follows:
typedef void(__stdcall *MyCallBack)(char*,char*,char*,char*,char*,char*,char*,
char*,char*,char*,int, int );
but the function that is assigned as the callback has this:
void MyCallbackRoutine(char* GetFeature,char* GetVersion,char* GetStartDate,
char* GetExpireDate, char* GetUsers,char* GetKey,
char* GetVendorString, char* GetHostID,
char* GetErrorMsg,char* GetLicense,
int GetCheckOutStatus, int nCount)
The number and type of parameters match up, the return type void matches, but the key element that doesn't match is that __stdcall is missing. By default, The calling convention is __cdecl if not specified. The correction should be:
void __stdcall MyCallbackRoutine(char* GetFeature,char* GetVersion,char* GetStartDate,
char* GetExpireDate, char* GetUsers,char* GetKey,
char* GetVendorString, char* GetHostID,
char* GetErrorMsg,char* GetLicense,
int GetCheckOutStatus, int nCount)
Note that the compiler should have picked up the issue when assigning a function who's definition doesn't match the prototype as this small example demonstrates (If this compiler error occurs, do not try to fix it by applying a C-style cast to shut the compiler up -- that is not a fix).
I made a code to convert time into minutes and seconds using constructor. In output I'm getting time in seconds but its not displaying time in minutes and can't figured out my mistake so anyone can help me out...
#include<iostream>
using namespace std;
class Time
{
public:
Time(int);
Time(float);
};
Time::Time(int t)
{
cout << "Time in seconds: " << t*60*60 << "\n";
}
Time::Time(float t)
{
cout << "Time in Minutes: " << int(t*60) << "\n";
}
int main()
{
int hr;
cout << "Enter the time in Hours: ";
cin >> hr;
Time t1(hr);
Time t2(float(hr));
}
You aren't typecasting correctly. You need to typecast by putting the desired type in parentheses, not by trying to use it as a function. For example, you'd need to do this:
Time t2((float) hr);
cout << "Time in Minutes: " << (int) t*60 << "\n";
While Time t2(float(hr)); is legal, it's a function prototype because this is a vexing parse. It is equivalent to Time t2(float hr);, which means that t2 is a function that takes a float called "hr" and returns a Time. This has no effect since such a function is never implemented or called.
If this seems absurd, here's a way to think about it that can help. Consider this code:
Time t2 (float (*hr));
Clearly this is a perfectly normal way to declare t2 as a function that takes a pointer to a float called "hr". Well, shouldn't it also be legal without the *? And the C++ grammar rule is that if something can be a prototype, it is.
Should works :
Time t2((float)hr);
Time::Time(int hour){
cout << "Time in seconds: " << hour*60*60 << "\n";
cout << "Time in minutes: " << hour*60 << "\n";
}
try adding
Time::Time(float t)
{
cout << "Time in Minutes: " << float(t*60) << "\n";
}
tell me if it works..
I'm experimenting a strange mktime() function behaviour. When I assign the value returned by the function, the value of the input parameter is one and when I doesn't the value is different.
I already know that mktime() adjust the values of the struct tm input parameter but what's happening it's different, lets see the code with the corresponding output:
First code
#include <iostream>
#include <time.h>
using namespace std;
int main(int argc, char** argv) {
struct tm cT;
strptime("31/07/2014 16:54:00", "%d/%m/%Y%n%T", &cT);
mktime(&cT);
cout << "Current Time: " << cT.tm_mday << "/" << cT.tm_mon + 1 << "/" << cT.tm_year + 1900 << " " << cT.tm_hour << ":" << cT.tm_min << ":" << cT.tm_sec << endl;
}
Output:
Current Time: 31/7/2014 16:54:0
Second code
#include <iostream>
#include <time.h>
using namespace std;
int main(int argc, char** argv) {
struct tm cT;
strptime("31/07/2014 16:54:00", "%d/%m/%Y%n%T", &cT);
time_t t = mktime(&cT);
cout << "Current Time: " << cT.tm_mday << "/" << cT.tm_mon + 1 << "/" << cT.tm_year + 1900 << " " << cT.tm_hour << ":" << cT.tm_min << ":" << cT.tm_sec << endl;
}
Output:
Current Time: 31/7/2014 15:54:0
Any help is welcome. :)
This is a classic case of forgetting to initialize a variable. Specifically, you need to initialize the cT variable with appropriate values for at least all fields that won't be touched by strptime (strptime will only set those fields corresponding to the input field descriptors in the format string).
Eg. :
struct tm cT = { 0 };
cT.tm_isdst = -1;
strptime("31/07/2014 16:54:00", "%d/%m/%Y%n%T", &cT);
This may be very simple but I am confused!
I am getting segmentation fault when extracting information from a pointer to a pointer. See the cout section in main(). Any help will be appreciated.
Thanks..
Sen
#include <stdlib.h>
#include <iostream>
typedef struct{
int hour;
int minute;
} Time;
Time* GetNextTime(void)
{
Time *p_time = new Time;
return p_time;
}
void GetTime( Time **sometime )
{
int length = 10;
sometime = new Time*[length];
for(int i=0; i<length; i++)
{
sometime[i] = GetNextTime();
sometime[i]->hour = rand()%24 ;
sometime[i]->minute = rand()%60;
std::cout << "Entered times " << sometime[i]->hour << " hour " << sometime[i]->minute << " minutes " << std::endl;
}
}
int main()
{
Time** _time;
GetTime( _time );
//here is the question
// I cant print them from original _time
for( int i=0; i<10; i++)
std::cout << " Print times " << (*_time)[i].hour << " hour " << (*_time)[i].minute << " minutes " << std::endl;
}
You're passing sometime by value, not by reference so it remains uninitialized. Change GetTime to the following:
void GetTime( Time ** &sometime ) //& means pass by reference
Because you're creating an array of pointers, you can use array notation to access them during printing as well.
std::cout << " Print times " << _time[i]->hour << " hour "
<< _time[i]->minute << " minutes " << std::endl;
Unless an argument is explicitly labelled as using a reference it is passed by value in C++. Thus, assigning to sometime in GetTime() has no effect on _time in main().
My strong advice is not to us explict memory allocation but use containers, e.g. std::vector<T>, instead. You'd still need to pass the container by refernence, however.
In main
It should be
Time *_time;
GetTime(&_time)
And then cout should be done with _time instead of *_time