Archived

This topic is now archived and is closed to further replies.

DrewSmug

Sleep() problem

Recommended Posts

i’m just playing with the Sleep() function and whenever i use it anywhere in my program it always executes first thing, for example… #include <iostream.h> #include <windows.h> int main(){ cout<<"hello world\n"; Sleep(1000); return 0; } this sleeps first and then prints hello world to the screen shouldn’t it do these commands the other way around any help or explanations appreciated thanks

Share this post


Link to post
Share on other sites
That would probably be because output using cout is buffered. Try calling cout.flush() right after cout << "hello world\n" . That will tell cout to shove everything to the screen that hasn''t yet actually made it there. Everything does indeed execute before the Sleep(1000) call, it''s just that they operate differently than you would expect in this case. But cout << "hello world\n" certainly was called before Sleep(1000) .


int Agony() { return *((int*)0); }    Mwahaha... >8)

Share this post


Link to post
Share on other sites
er, how do you know it sleeps first? It may just take a second for the console to load and display the text. You may be misinterpreting the startup time as the sleep time. Put another cout after the Sleep. Then you can just see if it prints Hello, waits a second and then prints the second statement.

Share this post


Link to post
Share on other sites
Agony has a correct answer, but you could just add endl to the end, like so...

cout<<"hello world\n"<<endl;    


Edit: Third time lucky!

[edited by - tiffany_smith on March 29, 2004 4:48:14 PM]

Share this post


Link to post
Share on other sites
As Agony said, it''s because it''s buffered. You could use std::endl, which automatically flushes the stream, unstead of ''\n'', or call std::cout.flush().

Share this post


Link to post
Share on other sites
quote:
Original post by Tiffany_Smith
Agony has a correct answer, but you could just add endl to the end, like so...

cout<<"hello world\n"<<endl;    


Edit: Third time lucky!

[edited by - tiffany_smith on March 29, 2004 4:48:14 PM]


... you''d probably want to remove the \n if you add an endl, yes? So... fourth time lucky?

Share this post


Link to post
Share on other sites