Search code examples
c++loopssleep

Printing characters in one line, with using sleep() function after each char


I have some difficulties with my "program". I would like to print text from my file to program in ONE line (horizontal position) using sleep() function after each char (using for loop), but it doesnt work. (In terminal I see blank space, nothing is printed).

    #include <iostream>
#include <fstream>
#include <unistd.h>
//#include <cstdlib>
using namespace std;

int main()
{
fstream plik;
string linia;
plik.open("ala.txt",ios::in);
getline(plik,linia);

    //string tekst;
    //tekst="Ala ma kota a kto ma Ale. Basia ma psa i rybki.";
    for(int i=0;i<=linia.length();i++)
    {
    cout<<linia[i];
    sleep(1);
    }

But when I use '\n' near "cout<<line[i]<<'\n';" , everything is OK but its printed in vertical position.

 #include <iostream>
#include <fstream>
#include <unistd.h>
//#include <cstdlib>
using namespace std;

int main()
{
fstream plik;
string linia;
plik.open("ala.txt",ios::in);
getline(plik,linia);

    //string tekst;
    //tekst="Ala ma kota a kto ma Ale. Basia ma psa i rybki.";
    for(int i=0;i<=linia.length();i++)
    {
    cout<<linia[i]<<'\n';
    sleep(1);
    }

Can You help me?


Solution

  • What you are missing is the flush side-effect of newline characters and std::endl. You will notice that if you wait long enough for the whole file to be printed (although the output is not flushed to the screen output), it will all appear at the same time when the system exits.

    To fix this, explicitly flush the output with std::flush

    cout<<i<<flush;