4

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";

    }
}
6502
  • 112,025
  • 15
  • 165
  • 265
sebek
  • 87
  • 1
  • 2
  • 8

3 Answers3

4

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));
    
Community
  • 1
  • 1
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
  • maybe because of [`cout`, not `std::cout`](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) :) – ikh Nov 03 '15 at 11:15
  • 1
    @ikh I just tried to adjust to the code of the OP, thus assuming a preceding `using` directive. – cadaniluk Nov 03 '15 at 20:59
1

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

6502
  • 112,025
  • 15
  • 165
  • 265
1

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)

Luis Colorado
  • 10,974
  • 1
  • 16
  • 31