Search code examples
c++operator-precedence

C++ commands executing out of order


I am attempting to make a simple shell program, and looking at a few examples have seen that most people use getline() to get input, however I have been trying to use read() and noticed a weird bug that I was wondering if other people saw or knew the cause of.

When I run the code using getline, everything works fine. After running the program I get the terminal name to show up and it is ready to accept input. When I use read it seems to be executing the name of the shell after taking in input. This seems to occur no matter what I do. the line to display the shell name is

cout << "SweetShell-> ";

and then AFTER this line I either run the read command, or even call another process which then runs the read command, and either way printing "SweetShell-> " happens AFTER the input.

Even weirder during testing I had a block of code like:

cout << "SweetShell-> ";
int test = read(0,buf,MAX_ARGS);
//temp is a string that is set to the input
cout << temp << "    " << test;

and the output looked something like this:

    3SweetShell-> ls

meaning it printed the spaces, then test, then the first cout, and finally temp. Anyone have any idea what is going on with this?


Solution

  • You should try "flushing" the output buffer to make sure it prints in order. Try:

    cout << "SweetShell-> " << std::flush;
    int test = read(0,buf,MAX_ARGS);
    //temp is a string that is set to the input
    cout << temp << "    " << test << std::flush;