News:

The new Release 25.03 is out! You can download binaries for Windows and many major Linux distros here .

Main Menu

Sleep Function - Searched The Whole Google Before Creating It

Started by dezt, March 31, 2011, 05:12:48 AM

Previous topic - Next topic

dezt

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:

#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.




stahta01

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.
C Programmer working to learn more about C++.
On Windows 10 64 bit and Windows 11 64 bit.
--
When in doubt, read the CB WiKi FAQ. [url="http://wiki.codeblocks.org"]http://wiki.codeblocks.org[/url]

dezt

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. ;)

MortenMacFly

Quote from: 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?
Quote from: stahta01 on March 31, 2011, 05:16:30 AM
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.
Compiler logging: Settings->Compiler & Debugger->tab "Other"->Compiler logging="Full command line"
C::B Manual: [url="https://www.codeblocks.org/docs/main_codeblocks_en.html"]https://www.codeblocks.org/docs/main_codeblocks_en.html[/url]
C::B FAQ: [url="https://wiki.codeblocks.org/index.php?title=FAQ"]https://wiki.codeblocks.org/index.php?title=FAQ[/url]