C++ Calling another C++ function with popen and getting the output

50 views Asked by At

I want to enter six integers, and that C++ program that is called returns some value (cout), but I find that the output is not printed until the program pclose(pipe). So that part of the fgets function in the middle doesn't get the value. I wonder why?

string run_command_and_get_result(const char* command, int input1, int input2, int input3, int input4, int input5, int input6) {
    FILE* pipe = popen(command, "w");
    if (!pipe) {
        cerr << "Error: popen() failed!" << endl;
        return "";
    }

    fprintf(pipe, "%d %d %d %d %d %d\n", input1, input2, input3, input4, input5, input6);

    fflush(pipe); 
    
    char buffer[MAX_RESULT_SIZE]; 
    string result = "";

    while (fgets(buffer, MAX_RESULT_SIZE, pipe) != NULL) {
        cout << "1-EVERY RESULT- " << buffer << endl;
        result += buffer;
    }

    pclose(pipe); 
    
    cout << "2-EVERY RESULT- " << result << endl;
    return result;
}

at least I see where the problem is but I still think it is strange.

0

There are 0 answers