0

Why is this not working. I Just want loading like effects. I just compiled the code the g++ compiler. It take time and just print * * * B R E A K * * *. There is no difference between per letter.

#include <iostream>
using namespace std;

int main()
{
    int wait = 1000000000;
    char text[] = {"* * * B R E A K * * *"};

    for(int i = 0; i < 21; i++)
    {
        cout << text[i];

        for(int j = 0; j < wait; j++)
            ;
    }
}
7
  • 1
    Why do you expect that there will be "difference between per letter"? Commented Aug 25, 2015 at 14:30
  • 1
    It appears to work as designed. What are you trying to do differently? Commented Aug 25, 2015 at 14:31
  • 2
    You can't rely on the second loop waiting at all, the whole thing could be optimized out. Commented Aug 25, 2015 at 14:32
  • Use some sort of timer to do the pause, the empty loop can be completely optimized out by an optimizing compiler. Also prefer std::string over char text[], it will make your life a lot easier. Commented Aug 25, 2015 at 14:34
  • possible duplicate of Sleep for milliseconds Commented Aug 25, 2015 at 14:34

1 Answer 1

6

Your wait loop is likely optimized out from the code because the compiler can see that it has no effect. Try to do a nano-sleep instead, like

#include <iostream>
#include <unistd.h>

using namespace std; 
int main()
{
   char text[]={"* * * B R E A K * * *"};
   for(int i=0;i<21;i++)
   {
      cerr<<text[i];
      usleep(100000);
   }
}

Also, std::cout is buffered, which means that it will not write until there is a newline, program terminates or you flush -- for simplicity change the cout to cerr which is non-buffered....

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks.. Maybe I can also flush the buffer using manipulator cout <<flush or cout.flush()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.