Running shell scripts in C ++

I wrote the following code:

#include <iostream>  
#include <stdlib.h> 
using namespace std; 
  int main() {  
  cout << "The script will be executed"; 
  system("./simple.sh");  
} 

But when I run it, the shell script is executed first.
What can I do to execute "cout <"? will the script be executed "first"?

+5
source share
4 answers

The output stream buffer stream should be sufficient. You can do it with

cout << "The script will be executed";
cout.flush();

Alternatively, if you plan to also print a newline, you can use std::endlone that implicitly clears the buffer:

cout << "The script will be executed" << endl;
+11
source

You do not clear the output stream.

Try:

cout << "The script will be executed" << endl; // or cout.flush()
system("./simple.sh");

The script runs the second, the delay between the call coutand printing to the console probably drops you.

+1
source

you can use cerr << "The script will be executed";
when you try to print something using cout, it saves it in the buffer. cerrprints right away, but @Jon responds better.

0
source

Try to clear the stdout stream before calling the system () system call.

0
source

All Articles