2012-02-22 250 views
5

我一直写如下因素代码:运行shell脚本++

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

但是当我运行它第一次执行shell脚本。
我能做些什么来执行“cout < <”该脚本将首先执行“”?

回答

11

刷新输出流缓冲区应该足够了。你可以用

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

或者做到这一点,如果你打算同时打印一个换行符,那么你可以使用std::endl含蓄地刷新缓冲区:

cout << "The script will be executed" << endl; 
0

可以使用cerr << "The script will be executed";
当你”重新尝试使用cout打印某些东西,它将它保留在缓冲区中。 cerr正在立即打印,但@Jon回答得更好。

0

尝试在调用system()系统调用之前清除stdout流。

1

您不会刷新输出流。

尝试:

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

该脚本执行第二次,调用cout和打印到控制台之间的延迟可能是你扔了。