Reputation: 83
I am trying to understand system calls made in c++ using system("some command"). here's the code
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
cout << "Hello ";
system("./pause");
cout << "World";
cout << endl;
return 0;
}
the executable "pause" is created from the following code
#include <iostream>
using namespace std;
int main()
{
cout<<"enter any key to continue\n";
cin.get();
return 0;
}
I get the following output
enter any key to continue
1
Hello World
Can someone please explain the output to me? I was expecting this -
Hello
enter any key to continue
1
World
Upvotes: 6
Views: 884
Reputation: 10007
The reason for the particular behavior that you observe seems to be just cout
buffering: the Hello
is not printed immediately, instead held in a buffer until endl
is output (or the buffer is filled completely, or you explicitly call flush()
). This is in no way related to a system()
call.
A simpler example:
cout << "Hello";
sleep(10);
cout << "World";
Both words will appear at the same time, not with a 10 seconds delay.
Upvotes: 5
Reputation: 12178
It's probably not a case of system call but output stream buffering.
cout << "xxx"
does not necessary outputs something, so program called by system
can be executed before cout
flushes it buffer to console.
try adding cout.flush()
after cout << "Hello"
or write cout << "Hello" << flush
also: cout << endl
automagically calls flush
Upvotes: 6
Reputation: 1
The answer on "how does system
library function works?" is usually operating system specific. See here for a Linux point of view. Notice that system
is not a system call and there is a priori no relation between using system(3) and having cout
buffer being flushed.
You should flush the stdout before calling system
cout << "Hello " << flush;
or preferably
cout << "Hello " << endl;
The behavior you are observing is because cout
is buffered and you forgot to flush the buffer.
Upvotes: 4
Reputation: 9617
system
runs a command in a shell. But your problem is not with system
but with cout
. cout
is line-buffered, ie. it won't flush (write out) its data until a new line character is encountered. You need to flush it explicitely with cout << flush
.
Upvotes: 6