I am making a command-line c++ application and I want text to be on a sort of timer because there is a lot of text. I already know how to make it so they have to press enter, but I want it to be automatic. What would be the simplest way to do this.
Example Output:
Welcome to the Calculator Game!
(1 second later) Do you want to play(Yes or No)?
The easiest thing is just to use `sleep(milliseconds)'. Most operating systems have varous ways of doing timers as well.
Even better if you are using C++11, use something like this:
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
std::cout << "Hello waiter" << std::endl;
std::chrono::milliseconds dura( 2000 );
std::this_thread::sleep_for( dura );
std::cout << "Waited 2000 ms\n";
}
If you're not using C++11, then try the following:
#include <time.h>
void sleep(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
Docs here: http://en.cppreference.com/w/cpp/thread/sleep_for
Related
I'm building a simple small program for fun, to kill time and learn something. I simply want my program to display local time (I live in Buffalo, NY, so I'm in ET). I put together an ostensibly ridiculous soup of libraries to ensure that my program is aware of everything:
#include <iostream>
#include <chrono>
#include <ctime>
#include <cstdlib>
#ifdef __unix__
# include <unistd.h>
#elif defined _WIN32
# include <windows.h>
#define sleep(x) Sleep(1000 * (x))
#endif
I tried the code from this page that uses the localtime() method:
#include <ctime>
#include <iostream>
int main() {
std::time_t t = std::time(0); // get time now
std::tm* now = std::localtime(&t);
std::cout << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday
<< "\n";
}
I also tried a chunk of code that uses the ctime() method from here > How to get current time and date in C++? :
#include <iostream>
#include <chrono>
#include <ctime>
int main()
{
auto start = std::chrono::system_clock::now();
// Some computation here
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished computation at " << std::ctime(&end_time)
<< "elapsed time: " << elapsed_seconds.count() << "s" <<
<< std::endl;
}
Every time I try something, my efforts are accompanied with the compiler stating the following:
Error C4996 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. 15Puzzle C:\Users\owner\source\repos\15Puzzle\main.cpp 10
... and when I follow that suggestion, the compiler states that the std library does not have the recommended method. I really don't want to disable anything cautionary.
What should I do?
(Ideas for the answer were contributed by Adrian Mole and n. 1.8e9-where's-my-share m. in the comments to the OP question.)
The C4996 is simply a stumbling block designed by Microsoft. To bypass this "error", simply set the _CRT_SECURE_NO_WARNINGS flag to true by adding the following to the very top of the main file:
#define _CRT_SECURE_NO_WARNINGS 1
There seems to be more than one theory as to why Microsoft would do this, but the truth is that there's really nothing wrong with using the chrono library's traditional functions.
I have an loop, but it goes to fast. I need something simple and easy to use, to pause it for 1 sec in each loop.
for(int i=0;i<=500;i++){
cout << "Hello number : " << i;
//i need here something like a pause for 1 sec
}
std::this_thread::sleep_for is exactly what you're looking for.
for(int i=0;i<=500;i++){
cout << "Hello number : " << i;
std::this_thread::sleep_for(1s);
}
To use it like that, you need to include <chrono> and <thread> and then add using namespace std::chrono_literals;. It also requires c++11 enabled.
Sleep(n) is a prepared method. To use this method do not forget to add "windows.h" header file as well and remember 'n' is the millisecond you may wish to delay the code execution. A simple code which repeats "Hello world!" can be seen:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
for(int i=0;i<10;i++)
{
cout << "Hello world!" << endl;
Sleep(1000);
}
return 0;
}
If you use windows platform this may help:
#include <windows.h> //winapi header
Sleep(1000);//function to make app to pause for a second and continue after that
I want to add a delay so that one line will run and then after a short delay the second one will run. I'm fairly new to C++ so I'm not sure how I would do this whatsoever. So ideally, in the code below it would print "Loading..." and wait at least 1-2 seconds and then print "Loading..." again. Currently it prints both instantaneously instead of waiting.
cout << "Loading..." << endl;
// The delay would be between these two lines.
cout << "Loading..." << endl;
in c++ 11 you can use this thread and crono to do it:
#include <chrono>
#include <thread>
...
using namespace std::chrono_literals;
...
std::this_thread::sleep_for(2s);
to simulate a 'work-in-progress report', you might consider:
// start thread to do some work
m_thread = std::thread( work, std::ref(*this));
// work-in-progress report
std::cout << "\n\n ... " << std::flush;
for (int i=0; i<10; ++i) // for 10 seconds
{
std::this_thread::sleep_for(1s); //
std::cout << (9-i) << '_' << std::flush; // count-down
}
m_work = false; // command thread to end
m_thread.join(); // wait for it to end
With output:
... 9_8_7_6_5_4_3_2_1_0_
work abandoned after 10,175,240 us
Overview: The method 'work' did not 'finish', but received the command to abandon operation and exit at timeout. (a successful test)
The code uses chrono and chrono_literals.
In windons OS
#include <windows.h>
Sleep( sometime_in_millisecs ); // note uppercase S
In Unix base OS
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
#include <unistd.h>
int usleep(useconds_t usec); // Note usleep - suspend execution for microsecond intervals
You want the sleep(unsigned int seconds) function from unistd.h. Call this function between the cout statements.
How do I delay an output in C++? I tried searching for similar questions, but I didn't find any solution which makes use of the 'ctime' library. Help please.
Have a look at this answer.
You could use std::this_thread::sleep_for(std::chrono::milliseconds(x));
For example:
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
int x{3000};
std::cout << "Start waiting\n";
std::this_thread::sleep_for(std::chrono::milliseconds(x));
std::cout << "Done waiting\n";
return 0;
}
I have searched but I can't find an equivalent to the matlab tic/toc function to simply display on the console how long time took the program to do its processing. (ideally I would like to put the tic (start timer) and toc (end timer) anywhere in the program.
Any suggestions?
I found what I was looking for.
Include:
#include <ctime>
Then at the beginning:
time_t tstart, tend;
tstart = time(0);
And finally before the end:
tend = time(0);
cout << "It took "<< difftime(tend, tstart) <<" second(s)."<< endl;
You can look at the boost date_time module which might be more portable.
If you are on linux you can use the function
clock_gettime();
if on windows try
QueryPerformanceCounter()
You can google these for specific implementation details. Other operating systems I dont know about. There are doubtless many other ways to achieve the same thing but if you get no other responses, these are a reasonable place to start.
By using std::chrono you can write a simple function that performs as Matlab's tic toc:
#include <iostream>
#include <chrono>
#include <thread> // sleep_for, for testing only
void tic(int mode=0) {
static std::chrono::_V2::system_clock::time_point t_start;
if (mode==0)
t_start = std::chrono::high_resolution_clock::now();
else {
auto t_end = std::chrono::high_resolution_clock::now();
std::cout << "Elapsed time is " << (t_end-t_start).count()*1E-9 << " seconds\n";
}
}
void toc() { tic(1); }
int main(int argc, char **argv)
{
tic();
// wait 5 seconds just for testing
std::chrono::seconds sleep_s(5);
std::this_thread::sleep_for(sleep_s);
toc();
return 0;
}