Sleep() problem
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
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)
int Agony() { return *((int*)0); } Mwahaha... >8)
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.
Agony has a correct answer, but you could just add endl to the end, like so...
Edit: Third time lucky!
[edited by - tiffany_smith on March 29, 2004 4:48:14 PM]
cout<<"hello world\n"<<endl;
Edit: Third time lucky!
[edited by - tiffany_smith on March 29, 2004 4:48:14 PM]
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().
the endl worked well
the buffer thing makes sense
thanks alot
[edited by - DrewSmug on March 29, 2004 4:59:17 PM]
the buffer thing makes sense
thanks alot
[edited by - DrewSmug on March 29, 2004 4:59:17 PM]
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?
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement