Search code examples
c++coutflushostream

Clearing the cout buffer (c++)


Hello I'm writing a short program to implement a shell and I'm running into an unusual problem. For some reason I can't clear to the std::cout buffer. The program wont print out messages. I understand a simple solution is to switch to std::cerr, but is there a way to get messages to print with cout? Things I've tryed:

  1. std::cout.flush()
  2. Inserting std::endl after anything is written to standard out.
  3. Inserting an std::flush into the output stream
  4. std::cout.setf(std::ios::unitbuf); which was something I found that should unbuffer output.

Any help is much appreciated here is my code:

int main()
{
    //Tryed this to unbuffer cout, no luck.
    std::cout.setf(std::ios::unitbuf);

    std::string input;

    //Print out shell prompt and read in input from keyboard.
    std::cout << "myshell> ";   
    std::getline(std::cin, input);

    //**********************************************************************
    //Step 1) Read in string and parse into tokens.
    //**********************************************************************

    char * buf = new char[input.length() + 1];
    strcpy(buf, input.c_str());

    int index = 0;
    char * command[256]; 

    command[index] = std::strtok(buf, " ");    //Get first token.
    std::cout << command[index] << std::endl;

    while (command[index] != NULL)
    {
        ++index;
        command[index] = std::strtok(NULL," ");    //Get remaining tokens.
        std::cout << command[index] << std::endl;
    }   

    std::cout.flush(); //No luck here either

    //HERE IS WHERE MY PROBLEM IS.
    std::cout << index << " items were added to the command array" << std::endl;

    delete[] buf;

    return 0;   
}

Solution

  • The problem is that you're sending NULL to cout on the last iteration of the while loop, which leads to UB, and in your case is jamming cout. Check for NULL before you send anything to cout and you're fine:

    if (command[index] != NULL) {
        std::cout << command[index] << std::endl;
    }