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
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 have an array that contains chars.
I am trying to print out an element once every second.
int i=0;
while (i< 110)
{
cout << arrayValue[i]<<"\0";
sleep(1);
i++;
}
This for some reason just waits for 110 seconds and than prints out the whole array at once.
But if i add a new line after every element it works just fine
int i=0;
while (i< 110)
{
cout << arrayValue[i]<<"\0";
cout<< endl;
sleep(1);
i++;
}
Any recommendation on how to get each element to print chronologically without having to make a newline?
This for some reason just waits for 110 seconds and than prints out the whole array at once.
Actually it doesn't, but your output is buffered. There is buffering in the C++ stream object, in the OS data pipe, and in your terminal.
Your stream thinks it would be a waste of resources passing characters through one at a time, and it's kind of right: the stream doesn't know you have a second to wait in between each one.
You don't need the newline, though; you can basically force a flush like so:
std::cout << std::flush;
Recall that std::cout << std::endl is equivalent to std::cout << '\n' << std::flush, and it's the '\n' part that you don't want.
This is usually enough but you may also need to reconfigure your terminal to turn off line buffering. (That's unlikely for output but quite common for input).
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 know this is a noob question. I used this example code from here. How is it supposed to work? I thought you can input something for who but it just closes immediately.
#include <iostream>
#include "getopt_pp_standalone.h"
using namespace GetOpt;
using namespace std;
int main(int argc, char* argv[])
{
string who;
GetOpt_pp ops(argc, argv);
ops >> Option('n', "name", who, "world" ); /* the default name is 'world' */
cout << "Hello " << who << "!" << endl;
return 0;
}
Variants of getopt get options from the command line rather than input by a user.
You will need to run your program with something like:
myprog -n Pax
If you want interactive input from the user, get rid of the getopt stuff altogether and just use the streams, such as:
std::cout << "Identify yourself, interloper!\n";
std::cin >> who;
std::cout << "Hello, " << who << ", my name is Pax.\n";
A few other things to impart:
First, you may need to put a getchar() (or cin >> who) before the return if you're running in an IDE that closes the execution window instead of waiting. Otherwise, the output will go to the window and immediately disappear.
Second, while it's probably okay for small programs, using namespace std can cause problems with more substantial projects (in terms of polluting the standard namespace, see here for a good explanation). I prefer to fully qualify my calls, such as:
std::cout << "blah, blah, blah\n";
Third, endl is used far too often by most developers. Most times you should just either use '\n' instead, or just tack on \n to the end of a string like "Hello, world!\n". That's because the \n way doesn't force possibly inefficient flushing of the stream like endl does. That's covered here.
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()