Sleep between 2 outputs issue

How come this runs normally

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <time.h>
using namespace std;

int main() 
{
	cout << "1" << endl;
	sleep(1);
	cout << "2" << endl;
	sleep(1);
	cout << "3" << endl;
	sleep(1);
	cout << endl << endl;

	return 0;
}


But when I take out the "endl" it stops functioning normally and the 123 print all at once

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <time.h>
using namespace std;

int main() 
{
	cout << "1";
	sleep(1);
	cout << "2";
	sleep(1);
	cout << "3";
	sleep(1);

	return 0;
}
Last edited on
Both of the snippets function "normally". The difference is that the first snippet flushes the output buffer each time because of the endl, while the second snippet only flushes the output buffer once at the end of the program when the stream is destructed.

Is the are way I could get the numbers to output on the same line with a 1 second delay in between each output?
flush the buffer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <time.h>
using namespace std;

int main() 
{
    cout << "1";
    cout.flush();
    sleep(1);
    cout << "2";
    cout.flush();
    sleep(1);
    cout << "3";
    cout.flush();
    sleep(1);

    return 0;
}
Thank you!
Topic archived. No new replies allowed.