Sleep() problem

Started by
5 comments, last by DrewSmug 20 years ago
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
Advertisement
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)
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke
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.
"When you die, if you get a choice between going to regular heaven or pie heaven, choose pie heaven. It might be a trick, but if it's not, mmmmmmm, boy."
How to Ask Questions the Smart Way.
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]
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().
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other player's eyes with his King.
the endl worked well
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