Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running shell scripts in c++

Tags:

c++

Ive been writing the folowing 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 << "The script will be executed"" first?

like image 660
user1215706 Avatar asked Feb 22 '12 08:02

user1215706


2 Answers

Flushing the output stream buffer should be enough. You can do this with

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

Alternatively, if you intended to also print a newline character then you can use std::endl which implicitly flushes the buffer:

cout << "The script will be executed" << endl;
like image 199
Jon Avatar answered Sep 23 '22 02:09

Jon


You're not flushing the output stream.

Try:

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

The script is executed second, the delay between the call to cout and printing to the console is probably throwing you off.

like image 37
Luchian Grigore Avatar answered Sep 20 '22 02:09

Luchian Grigore