Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does the function system() work in c++?

Tags:

c++

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
like image 863
aseembits93 Avatar asked Jul 28 '15 11:07

aseembits93


2 Answers

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.

like image 72
StenSoft Avatar answered Oct 13 '22 17:10

StenSoft


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

like image 26
Hcorg Avatar answered Oct 13 '22 15:10

Hcorg