Outputting by specific time

Hi, i'm new to C++, i was given an assignment to create a simple program for traffic control. i'm trying to find out how should i output data at a specific time, for e.g a driver approaches an intersection, the yellow light will flash indicating that he needs to slow down and then the red light to stop before taking a route. is there any function i can use to output red light a few seconds after yellow light. or does anybody have an idea to do it differently. i'd appreciate it if you just tell me what i need to kno and then i reasearch it myself.. thanks
You should have something checking the time. You can get the time with time() (#include <ctime>). Time is a floating-point value expressed in seconds.

Subtract a previous time from the current time to get the number of seconds elapsed.

Hope this helps.
im trying to understand this but its a bit difficult.. can you explain a bit more please. im not sure if you really understood what i wanna do or if its just me..
// indicating driver should slow down when yellow light flashes
cout << "Yellow Light\n";

// indicating driver to stop before taking any routes at intersection
cout << Red Light\n";

what i wanna do is after yellow light prints i wanna output Red Light literally 5 seconds after yellow light has printed to screen. the 5 seconds will be for the time driver takes after slowing down n reaching the intersection. is this possible or is there another way to go about this.
Yes. Like Duoas said, you can use time() to get the time when you output the yellow light, then check time() to see how many seconds have elapsed. If it is at least 5, output red light.
ok tanks makes alot ofsense now lol.. tnks alot
Last edited on
here is my try out code i won't get the second print dont know what i'm doing wrong. can someone please help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <ctime>

using namespace std;

int main ()
	{

        time_t start_t, end_t;
        double diff_t;

        cout << "first print\n";
        time(&start_t);

        time(&end_t);
        diff_t = difftime(end_t, start_t);

// output after 5 seconds
        if(diff_t == 5.0)
            {
                cout << "second print\n";
            } // end while

	   return 0;

	} // end main 
Last edited on
i can tell that the if statement is not appropriate but i have no idea what to use
You have to use the while statement....

while the difftime < 5.0 do nothing loop
If you're new to c++ then I think you should not worry about the time, or the graphics: all of this will come with the libraries you will use. They all will have different time management functions and everything..
Also just have a look over std::sleep

Edit or if you use c++11 #include <chrono>
Last edited on
thanks much everyone for your help
Topic archived. No new replies allowed.