Code::Blocks Forums

Developer forums (C::B DEVELOPMENT STRICTLY!) => Development => Topic started by: dezt on March 31, 2011, 05:12:48 am

Title: Sleep Function - Searched The Whole Google Before Creating It
Post by: dezt on March 31, 2011, 05:12:48 am
Sorry for creating this topic, but I've searched the whole Google for this solution, but I didn't found it.

In Windows, my app works fine with those <windows.h> and the Sleep (with upper S), then I went to Linux and started to re-learn C++ into it.

Installed Codeblocks normally, I can compile other programs normally, but when I use the sleep function, the system waits the whole sleep before printing the countdown correctly (as in Windows).

I think isn't a Codeblocks problem, it's probably an mistake commited by me.

The code:

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

using namespace std;

int main ()
{

    string login;
    string pass;
    int n=3;


    cout << "Login: ";
    cin >> login;
    cout << "Password: ";
    cin >> pass;
    cout << "Checking password...\n";
    cout << "Authenticating in ";

    while (n>0) {
          cout << n << " ";
        sleep(3);
        --n;

              }
    cout << "\n";
    if (login=="dezt" && pass=="test")
        cout << "System Authenticated.\n";

    else
        cout << "Access denied.\n";


    return 0;
}

I've tried a bunch of variations to make the countdown works properly, but the program waits 3 seconds, then print all at once the 3 2 1 and boom, without the fashion 3 (wait) 2 (wait) 1 (wait) ok.

OBS again: In Windows, it worked correctly (with changes in headers).

If this topic is inappropriate, please delete it.



Title: Re: Sleep Function - Searched The Whole Google Before Creating It
Post by: stahta01 on March 31, 2011, 05:16:30 am
It is NOT an valid Code::Blocks post; but, you need to use endl and/or flush (not sure exact name) command with output if you wish it to have a close to real time effect.

Tim S.
Title: Re: Sleep Function - Searched The Whole Google Before Creating It
Post by: dezt on March 31, 2011, 05:29:09 am
Wow, thanks, it worked, but there's an way similar do endl, to not go to the next line?

Like, 3 2 1?

Again, thanks alot, this was an light in the dark for me. ;)
Title: Re: Sleep Function - Searched The Whole Google Before Creating It
Post by: MortenMacFly on March 31, 2011, 06:21:59 am
Wow, thanks, it worked, but there's an way similar do endl, to not go to the next line?
flush (not sure exact name) command
std::cout.flush().

Consult a C++ documentation for further help. This topic is locked now as it is far beyond the scope of this forum.