【问题标题】:No output is shown when I'm executing C++ from java code当我从 java 代码执行 C++ 时没有显示输出
【发布时间】:2018-05-23 18:51:14
【问题描述】:

知道只有在关联的 c++ 代码 (code.cpp) 中没有输入流时它才会给出输出,因此下面的代码没有输出:

        String command = "g++ -o code.bin code.cpp";
        Process p = Runtime.getRuntime().exec(command);

        p.waitFor();
        System.out.println("exit: " + p.exitValue());
        p.destroy();


        Process p1 = Runtime.getRuntime().exec("./code.bin < input.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(p1.getInputStream()));

        String line = "";
        while((line = br.readLine())!=null){
            System.out.println(line);
        }
        p1.waitFor();
        System.out.println("exit: "+p1.exitValue());
        p1.destroy();

例如,这段代码会给出一个输出:

    #include<iostream>
    using namespace std;
    int main(){
        cout<<"hello world\n";
        return 0;
    }          

虽然这段代码没有:

    #include<iostream>
    using namespace std;
    int main(){
       int x;
       cin>>x;
       cout<<x<<endl;
       return 0;
    }

我在终端中执行了命令,它给出了想要的输出,所以有人知道这背后的原因吗?

【问题讨论】:

    标签: java c++ terminal command


    【解决方案1】:

    迟到的答案。在我的类似情况下,用fflush(stdout) 刷新输出缓冲区证明是有效的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多