Reputation: 95
hello i am trying to get the output one time in while loop
While(1){
if( current->tm_hour == 10 && current->tm_min == 0 ){
Start_Function();
std::cout << "Started" << std::endl;
}
if( current->tm_hour == 12 && current->tm_min == 0 ){
End_Function();
std::cout << "Ended" << std::endl;
}
Sleep(5000);
}
and i use sleep to refresh every 5 sec
so i want when the current Hour & minut = 10 & 00
it give me output Started and it call the function just one time and it contiune refreshing
Upvotes: 1
Views: 1799
Reputation: 41862
How about:
bool start_called = false, end_called = false;
While(1){
if( current->tm_hour == 10 && current->tm_min == 0 && !start_called ){
Start_Function();
std::cout << "Started" << std::endl;
start_called = true;
} else
start_called = false;
if( current->tm_hour == 12 && current->tm_min == 0 && !end_called ){
End_Function();
std::cout << "Ended" << std::endl;
end_called = true;
} else
end_called = false;
Sleep(5000);
}
You could do it better with functors but that's a little more advanced.
Upvotes: 2
Reputation: 4528
Edit: In light of @Joachim Pileborg's comment
It's not the output that's the problem, it's that the functions are called (and the output printed) multiple times when it shouldn't. – Joachim Pileborg
Alternate solution
int hasStarted = 0, hasEnded = 0;
While(1){
if( current->tm_hour == 10 && current->tm_min == 0 && !hasStarted ){
Start_Function();
std::cout << "Started" << std::endl;
hasStarted = 1;
}
if( current->tm_hour == 12 && current->tm_min == 0 && !hasEnded ){
End_Function();
std::cout << "Ended" << std::endl;
hasEnded = 1;
}
Sleep(5000);
}
}
The code above will force it to only do each of the operation's once and continue refreshing...
My original comment:
In the command line/terminal as you've foundout the output is printed out continuously. Depending on what operating system you use (window/linux/mac) the solution will be easy or not so easy.
I recommend looking up the gotoxy()
function
http://www.programmingsimplified.com/c/conio.h/gotoxy
provided by the "conio.h" library for Windows or "ncurses.h" for Linux.
"ncurses.h" doesn't have the gotoxy()
but it will provide you with a way to do the same.
Upvotes: -1