How to get time in a class
Jul 10, 2016 at 1:09pm UTC
Hi, I am trying to print the hour and minute every time an object of a class (Time) is created.
I can get the time using the code below in my main function, but every time I try to put it inside my Time.cpp constructor, I get an error saying I have not declared clock_t.
So how should I do it? Thanks.
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include <ctime>
using namespace std;
#include "Time.h"
Time::Time()
{
time_t t = time(0);
struct tm * now = localtime( & t );
cout << now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec << endl;
}
Last edited on Jul 10, 2016 at 1:09pm UTC
Jul 10, 2016 at 2:19pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
#include <ctime>
class X{
public :
X() { timestamp(); }
void timestamp();
};
void X::timestamp()
{
time_t t = time(0);
struct tm * now = localtime( & t );
std::cout << now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec << '\n' ;
}
int main()
{
X x;
return 0;
}
14:18:31
Exit code: 0 (normal program termination)
Jul 10, 2016 at 2:22pm UTC
That's strange since you are not even using clock_t. What do Time.h look like?
Jul 11, 2016 at 6:03am UTC
@kemort, When I try copy pasting your code in my main.cpp it works. But when I try to seperate it into .h and .cpp file I get the same error.
@Peter87. here are my files,
X.h
1 2 3 4 5 6 7 8 9
#ifndef X_H
#define X_H
#include <ctime>
class X{
public :
X();
void timestamp();
};
#endif // X_H
X.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <ctime>
#include "X.h"
using namespace std;
X::X()
{
timestamp();
}
void X::timestamp()
{
time_t t = time(0);
struct tm * now = localtime( & t );
cout << now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec << '\n' ;
}
main.cpp
1 2 3 4 5 6 7 8 9
#include <iostream>
#include <ctime>
using namespace std;
#include "X.h"
int main()
{
X x;
}
Last edited on Jul 11, 2016 at 6:04am UTC
Jul 11, 2016 at 6:40am UTC
XTime.cpp
1 2 3 4 5 6 7
#include "X.h"
int main()
{
X x;
return 0;
}
X.h
1 2 3 4 5 6 7 8 9 10
#ifndef X_h
#define X_h
class X{
public :
X() { timestamp(); }
void timestamp();
};
#endif
X.cpp
1 2 3 4 5 6 7 8 9 10
#include "X.h"
#include <iostream>
#include <ctime>
void X::timestamp()
{
time_t t = time(0);
struct tm * now = localtime( & t );
std::cout << now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec << '\n' ;
}
16:36:1
Program ended with exit code: 0
@codebusters This is what XCode produces. I haven't looked at yours carefully but I think you need to address the order and disposition of the #includes. Only put them in where you need them. Blanket #includes often don't jag the right answer. :)
Last edited on Jul 11, 2016 at 6:51am UTC
Jul 11, 2016 at 2:18pm UTC
@kemort, Thanks so much! I don't know where I was going wrong, but it works now.
Topic archived. No new replies allowed.