Search code examples
c++clion

cannot make C++ stdout flush


I'm a beginner at C++, and was thinking of starting an app that integrates lua as an extension language. I copied the bare-bones REPL code below from somewhere and lightly adapted it to C++, but "at end", and "fprintf at end", do not appear when I run in release mode after I terminate input with Ctrl+D, despite my multiple flush call variants, but do appear when I run in debug mode, even without any breakpoints. It's a rather demoralizing start to what should be the easy part; what am I missing? I am running on MacOs in CLion with the clang toolchain provided by XCode if it matters.

#include <iostream>

extern "C" {
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}

int main() {
    std::cout << "at beginning" << std::endl;
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    for (std::string line; std::getline(std::cin, line);) {
        const char *cLine = line.c_str();
        int error = luaL_loadstring(L, cLine) || lua_pcall(L, 0, 0, 0);
        if (error) {
            const char *luaOut = lua_tostring(L, -1);
            std::cerr << luaOut << std::endl;
            lua_pop(L, 1);
        } else {
            std::cout << "output above a result of evaluating: ["
                      << line
                      << "]"
                      << std::endl;
        }
    }
    lua_close(L);
    std::cout << "at end" << std::endl;
    fprintf(stdout, "fprintf at end\n");
    std::flush(std::cout);
    std::cout.flush();
    fflush(stdout);
    fflush(NULL);
    return 0;
}

example session below:

at beginning
print(2 ** 3)
[string "print(2 ** 3)"]:1: unexpected symbol near '*'
print(2 ^ 3)
8.0
output above a result of evaluating: [print(2 ^ 3)]
print("hope this works, too")
hope this works, too
output above a result of evaluating: [print("hope this works, too")]
^D

Update

If I comment out the loop, the std::cout statements at the end work as expected. If I comment out the body of the loop, but leave the for statement intact, the std::cout statements after the loop do not work.

Second Update

After running from the terminal and seeing everything work, and reading the comments below, it seems that problem is not with the C++ code, but CLion. I am adding the CLion tag. If I cannot find a solution to this very worrying problem I will abandon CLion, which is disappointing as I like all the other JetBrains IDE's a lot.


Solution

  • It turns out this was not a problem with the code in any iteration. The problem is that CLion has an old and unfixed bug:

    https://youtrack.jetbrains.com/issue/CPP-5704

    Disabling run.processes.with.ptty gave me the output I expected.