Ok, this is just out of curiousity, but why does the sleep function NOT work in a loop, or how can I Get it to work in a loop?
for(int i = 0; i < 5; i++) {
cout << i << endl;
sleep(2);
}
cout is buffered, meaning its contents aren't always written to the console right away. Try adding cout.flush() right before sleep(2);
If that isn't working for you you could try this code:
#include <iostream>
#include <windows.h>
...
for(int i = 0; i < 5; i++) {
cout << i << endl;
Sleep(2000);
}
Have you tried unrolling the loop to see if that behaves the same way?
cout << 1 << endl;
sleep(2);
cout << 2 << endl;
sleep(2);
// Etc.
Assuming that behaves the same way, even though std::endl is supposed to flush the buffer, it really does look like dave.kilian has the right idea that cout isn't getting flushed until the program (presumably) terminates.
In that case, try doing the std::flush and see if that helps - it's possible you have a bug (missed feature?) in your standard library.
Another thing to try is to redirect the output to a file while watching it with tail -f in another window. See if the same delay occurs when redirected.
Finally try playing with the compiler's optimization level and see if that changes the results.
In my humble opinion, this program should work correctly. Maybe your std::cout is redirected somewhere else? You don't call the correct sleep() function (but no header provided)? Or other problem? But it should work.
Dave has already given you the answer, so I won't touch on that. However, if its purely for debugging or prototype code, you could also pipe the output to std::cout's sibling, std::cerr, which is unbuffered to begin with. This means you do not need to call flush explicitly and you do not need to add an endl to your output.
Try Sleep() instead of sleep()
Related
#include <iostream>
#include <thread>
using namespace std;
int main()
{
for (int i = 0; i < 10000; i++) {
cout << "Hello\n";
}
this_thread::sleep_for(chrono::milliseconds(2000));
cout << "2 seconds have passed" << endl;
return 0;
}
In my code, I didn't call any std::flush or std::endl, but the hello's are printed before the 2 seconds delay. I am expecting to print all the hello's after the 2 seconds delay, but it didn't. My code runs like this:
Hello
Hello
.
.
.
Hello
Hello
(after 2 seconds)
2 seconds have passed
[terminated]
Why is this happening?
First of all, you're writing more output than a typical file buffer will hold, so you'd almost always expect at least some of the output to show up before the sleep.
Second, you're doing a lot of separate output calls, so if cout is unit-buffered, each one is going to be flushed immediately.
Third, you're writing a new-line at the end of each item, so if cout is line-buffered, (yup) each one is going to be flushed immediately.
So, if you want a better chance of seeing at least some of the output showing up after the sleep ends, turn off unit buffering and get rid of the new-lines:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main()
{
cout << nounitbuf;
for (int i = 0; i < 1000; i++) {
cout << "Hello";
}
// display something different to make it easier for user to see
// whether all output showed up before sleep or not.
cout << "...";
this_thread::sleep_for(chrono::milliseconds(2000));
cout << "2 seconds have passed" << endl;
return 0;
}
But even with this, there's no guarantee the behavior will change. Rather the contrary, most implementations go to some pain to assure that output written to the console shows up as promptly as possible, so even when you take steps toward delaying it, it'll still probably show up before the sleep. But this might improve your chances a little bit anyway.
I want some random characters to be printed to console and then deleted by "\b". After this I want to put my own variable so it will be looking like "randomizing". The problem is that it is happening too fast. I wanted to delay the output by using usleep or sleep function but when I'm using it, nothing is printed into console.
Short example:
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
char chars[]={'a','b','c','g','h','u','p','e','y'};
for(int i=0; i<8; i++)
{
cout << chars[i];
usleep(200000);
cout << "\b";
}
}
Problem is, std::cout is line-buffered. It stores all input in a buffer until a newline is encountered (or the program terminates). Use std::flush to flush std::cout explicitly:
cout << chars[i] << flush;
Notes:
since C++11, multithreading and time are standardized. That brings the std::this_thread:sleep_for function with it, which you should use for a portable >= C++11 program:
std::this_thread::sleep_for(std::chrono::milliseconds(200));
Try my little program slowtty from github.
It allows you to simulate in a pty the behaviour of an old rs232c line, by delaying the output per character as stty(1) command allows to set the baudrate.
You call it with
$ slowtty
$ stty 1200
$
and the terminal begins to write characters at a slow pace (like a 1200baud line)
On many systems output is buffered.
To ensure that what you sent out to cout has really been flushed out of buffers you need to call
cout.flush();
before the sleep
Before you start wasting your time on me, please keep in mind that this question is more about knowing if this shutdown is legit enough.
Alright.
I read all kinds of ways to shut down a program. I KNOW that it's always best to shut down the program, at the end! So as i said, i read all kinds of topics, but i couldn't really find one that i understood correctly. So i kinda came up with my own way. I just want to make sure it's an okay method.
int main()
{
cout << "Welcome to my fantastic program!" << endl;
cout << "You're the first one to experience my command program!" << endl;
cout << "Let's try with a simple command. Try typing help" << endl;
while (running == 1) {
commands();
if (running == 0) {
exit(0);
}
}
return 0;
}
So i want you to focus on the while loop. This is my method.
void commands()
{
cin >> command;
if (command == "help")
{
cout << "-------------------------------" << endl;
cout << "-this is the <HELP> section----" << endl;
cout << "-exit (exits the program.)" << endl;
cout << "-Stay tuned for more commands--" << endl;
cout << "-------------------------------" << endl;
}
else if (command == "exit")
{
running = 0;
}
else
{
cout << "The command does not exist: " << command << endl;
}
}
And this is my command function. As you see, this changes "running" to 0 (or false). I hope i made this understandable enough.
Thanks.
EDIT: All i want to know is, if this is an okay method :)
FINAL EDIT: Alright! I changed "exit(0);" to "return(0);". So i guess this is a okay good method! Thanks for your help! :)
Using exit() in a program is legal. Though it's generally a bad idea. But if the program is stuck without a way back for some weird reason, you can do it.
Using exit in main() is rude: I just can't think of a sane reson not to use return instead.
The difference between exit() and return from main is that the former will leave all local objects in stack frames from main to the call point hanging, destructor not called. Only the static/global objects get proper shutdown. It may surprise some portions of the code, and leave important things not done.
As C++ has fine exceptions, I'd consider it preferable to replace exit() with throwing something that manages up to main, where regular return happens.
The if (running == 0) but is pointless!
while (running == 1) {
commands();
}
return 0;
Does exactly the same - once running is 0 it falls out the bottom of the loop, and main returns. The whole idea of the global running is getting into side effect programming, which is a bad thing!
Given the boundary conditions in the question exit() does what you want it to. It terminates the process normally, performing the regular cleanup for terminating programs (atexit(), destroying objects without automatic storage etc).
You don't really want to use a global running, so I would rather suggest checking the return parameter of commands().
say
int commands()
{
if(wanna_exit)
return 1;
else
return 0;
}
And if you for some reason cannot just let commands() break the while loop (For example by checking the return parameter and setting running to 0 if it is 1), and you want to exit the program instantly rather than finishing evaluating the rest of the while loop then exit() is ok (although in this particular case return is better (since you are in main in the example) ). Just try to avoid having running as global - might seem innocent right now, but can turn mean later :).
My code look like below
int i=0;
while(i<10){
cout<<"Hello";
sleep(1);
i++
}
In Windows the code prints on each loop but in Linux it prints everything after exiting while loop . And also if I put an endl at the last of cout then it prints on each loop. Why this happening ?. Can anyone explain this behavior?.
Try to use cout.flush(); maybe the two OS has different policy in term of buffering the stdout.
For efficiency reasons, sometimes the standard streams will be implemented with a buffer. Making lots of tiny writes can be slow, so it will store up your writes until it gets a certain amount of data before writing it all out at once.
Endl forces it to write out the current buffer, so you'll see the output immediately.
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while(i < 10){
cout << "Hello" << endl;
sleep(1);
++i;
}
}
I'm having this weird problem. My code is simple:
#include <iostream>
using namespace std;
int main() {
int num;
cout << "number: ";
cin >> num;
for (int i=0;num>i;i++) {
cout << i <<"\n";
}
system ("Pause");
return 0;
}
If the input for example is 1000, the output contains numbers from 701-999.
Any idea?
I'm using Dev-C++ IDE on Parallels.
Actually it prints all of them, from 0 to 999, but your console's buffer is not large enough. So you see only the last part. if you print into a file, not the console, you'll see :)
The loop ends when num>i is no longer true. This occurs when i is 1000, so the last loop executed will be with value 999. As for not seeing lower than 701, maybe your screen buffer is too small.
It will start with 0-999. Also, it appears to you that it starts with 701 because of your console screen settings. If you want to see it for yourself, change the newline into a space:
cout << i <<" ";
Did 0-700 scroll off the screen? Run your exe like this
your_program > out.txt
Then look at out.txt in an editor.
Works absolutely fine for me. I'd suggest your IDE might be playing tricks on you. Could you redirect output into a file and check that?
Regarding #JoshD answer,
You will need to:
for (int i=0;num>=i;i++) {
cout << i <<"\n";
}