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
                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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With