How does the system () function work in C ++?

I am trying to understand system calls made in C ++ using a system ("some command"). here is the code

#include <iostream> #include <cstdlib> using namespace std; int main() { cout << "Hello "; system("./pause"); cout << "World"; cout << endl; return 0; } 

an 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 explain the conclusion to me? I was expecting this -

 Hello enter any key to continue 1 World 
+5
source share
4 answers

The reason for the specific behavior that you are observing is simply cout buffering: Hello not printed immediately, but stored in the buffer until endl (or the buffer is full or you explicitly call flush() ). This has nothing to do with calling system() .

The simplest example:

 cout << "Hello"; sleep(10); cout << "World"; 

Both words will be displayed simultaneously, and not with a delay of 10 seconds.

+5
source

This is probably not a case of a system call, but buffering the output stream.

cout << "xxx" not required to produce something, so the program called by system can be executed before cout flushes the buffer to the console.

try adding cout.flush() after cout << "Hello" or write cout << "Hello" << flush

also: cout << endl automatically calls flush

+5
source

system runs a command in the shell. But your problem is not in system , but in cout . cout buffered by line, i.e. he will not unload (write out) his data until a new line symbol is encountered. You must explicitly flush it with cout << flush .

+5
source

The answer to the question: "How does the system library function work?" usually depends on the operating system. See here for a Linux perspective. Note that system not a system call, and between using (3) and flushing the cout buffer.

Before calling system

  cout << "Hello " << flush; 

or preferably

  cout << "Hello " << endl; 

The behavior you observe is due to the fact that cout buffered, and you forgot to flush the buffer.

+4
source

All Articles