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;
}
Related
I am trying to use boost file_lock to control two processes. I have process 1 obtaining a lock and then sleeping:
#include <boost/interprocess/sync/file_lock.hpp>
#include <fstream>
#include <chrono>
#include <thread>
int main()
{
std::string lock_path = "lockfile";
std::ofstream stream(lock_path, std::ios::app);
boost::interprocess::file_lock lock(lock_path.c_str());
if (lock.try_lock())
{
std::this_thread::sleep_for(std::chrono::seconds(30));
}
return 0;
}
while this process is sleeping, I will run a second process which tries to obtain the lock as well.
#include <boost/interprocess/sync/file_lock.hpp>
#include <iostream>
int main()
{
boost::interprocess::file_lock lock("lockfile");
if (lock.try_lock())
{
std::cout << "got here" << std::endl;
}
return 0;
}
I am expecting the cout statement on the second process not to print because the file is already locked by another process but it does print. What am I missing here? is file_lock not supposed to be used this way?
The best explanation I can think of is when your processes accidentally refer to different files. This might occur when
the current working directories are not the same
the processes run in isolated environments altogether (e.g. dockerized)
the file has been deleted/recreated in the meantime (meaning the inode doesn't match, even though the filename does)
Here's a simplified program that can serve as both parties:
Live On Coliru
#include <fstream>
#include <iostream>
#include <thread>
#include <boost/static_assert.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
namespace bip = boost::interprocess;
using namespace std::chrono_literals;
static inline auto constexpr lock_path = "lockfile";
int main() {
bip::file_lock lock(lock_path);
if (lock.try_lock()) {
std::ofstream stream(lock_path, std::ios::app);
std::cout << "got lock" << std::endl;
std::this_thread::sleep_for(2s);
}
std::cout << "bye" << std::endl;
}
Local demo:
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 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
Is there a C++ equivalent to Python's time.sleep()?
Use boost::this_thread::sleep
// sleep for 5 seconds
boost::this_thread::sleep(boost::posix_time::seconds(5));
The following code will sleep for 10 milliseconds.
boost::this_thread::sleep(boost::posix_time::milliseconds(10))
Refer to boost::posix_time::time_duration for more ways to construct the duration.
I'm not aware of any portable function, but mainstream OSes have usleep for *nix and Sleep for Windows.
Please note that the code above was tested on Code::Blocks 12.11 and Visual Studio 2012
on Windows 7.
For forcing your programme stop or wait, you have several options :
sleep(unsigned int)
The value has to be a positive integer in millisecond.
That means that if you want your programme wait for 2 second, enter 2000.
Here's an example :
#include <iostream> //for using cout
#include <stdlib.h> //for using the function sleep
using namespace std; //for using cout
int main(void)
{
cout << "test" << endl;
sleep(5000); //make the programme waiting for 5 secondes
cout << "test" << endl;
sleep(2000); // wait for 2 secondes before closing
return 0;
}
If you wait too long, that probably means the parameter is in second. So change it like that :
sleep(5);
For those who get error message or problem using sleep try to replace it by _sleep or Sleep especially on Code::Bloks.
And if you still getting probleme, try to add of one this library on the biggining of the code.
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <dos.h>
#include <windows.h>
system("PAUSE")
A simple "Hello world" programme on windows console application would probably close before you can see anything. That the case where you can use system("Pause").
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
system("PAUSE");
return 0;
}
If you get the message "error: 'system' was not declared in this scope" just add
the following line at the biggining of the code :
#include <cstdlib>
cin.ignore()
The same result can be reached by using cin.ignore() :
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
cin.ignore();
return 0;
}
cin.get()
example :
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
cin.get();
return 0;
}
getch()
Just don't forget to add the library conio.h :
#include <iostream>
#include <conio.h> //for using the function getch()
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
getch();
return 0;
}
You can have message telling you to use _getch() insted of getch
How does one "pause" a program in C++ on Win 32, and what libraries must be included?
#include <windows.h>
Sleep(number of milliseconds);
Or if you want to pause your program while waiting for another program, use WaitForSingleObject.
In C++11, you can do this with standard library facilities:
#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::milliseconds(x));
If you are using boost, you can use the thread::sleep function:
#include <boost/thread/thread.hpp>
boost::system_time time = boost::get_system_time();
time += boost::posix_time::seconds(1);
boost::thread::sleep(time);
Otherwise, you are going to have to use the win32 api:
#include <windows.h>
Sleep(1000);
And, apparently, C++0x includes this:
#include <thread>
std::this_thread::sleep_for(chrono::seconds(1));
Please note that the code above was tested on Code::Blocks 12.11 and Visual Studio 2012
on Windows 7.
For forcing your programme stop or wait, you have several options :
sleep(unsigned int)
The value has to be a positive integer in millisecond.
That means that if you want your programme wait for 2 second, enter 2000.
Here's an example :
#include <iostream> //for using cout
#include <stdlib.h> //for using the function sleep
using namespace std; //for using cout
int main(void)
{
cout << "test" << endl;
sleep(5000); //make the programme waiting for 5 secondes
cout << "test" << endl;
sleep(2000); // wait for 2 secondes before closing
return 0;
}
If you wait too long, that probably means the parameter is in second. So change it like that :
sleep(5);
For those who get error message or problem using sleep try to replace it by _sleep or Sleep especially on Code::Bloks.
And if you still getting probleme, try to add of one this library on the biggining of the code.
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <dos.h>
#include <windows.h>
system("PAUSE")
A simple "Hello world" programme on windows console application would probably close before you can see anything. That the case where you can use system("Pause").
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
system("PAUSE");
return 0;
}
If you get the message "error: 'system' was not declared in this scope" just add
the following line at the biggining of the code :
#include <cstdlib>
cin.ignore()
The same result can be reached by using cin.ignore() :
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
cin.ignore();
return 0;
}
cin.get()
example :
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
cin.get();
return 0;
}
getch()
Just don't forget to add the library conio.h :
#include <iostream>
#include <conio.h> //for using the function getch()
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
getch();
return 0;
}
You can have message telling you to use _getch() insted of getch
If you wish for the program to stay responsive while "paused", you need to use a timer event.
It depends on what type of program you are writing.
A console app can just call Sleep. A GUI app probably does not want to do this, as all the menus and widgets will go insensitive, and the app won't redraw itself during this period. Instead you need to do something like set yourself up a timer with a callback when it expires.
Dont use a sleep function in your GUI if it is not provided by the framework you are working with. This could create referencing problems to data (specially in a thread that is not the main thread). This could freeze you GUI. Its not just a question of sleeping for a short time , use waitmutexes if you need to do that.