[C++] I'm Stuck: How to directly react on the pressed Tab Key?

I’m stuck on Stage #(QP2).

I’ve previously read all my commands as one line with getline().
I now use getchar(), but pressing the Tab-Key still does not lead to any direct result. It leads to a result, but I first need to tap enter(\n) after pressing it.

Here is the relevant function in my C++ code:


void CommandReader::readCharacterByCharacter(std::string &currentInput, CommandManager &manager) {
    char c;
    while (true) {
        c = static_cast<char>(getchar());
        if (c == '\n') {
            return; // Input line completed
        } else if (c == '\t') {
            // Autocompletion for Tab Key
            std::vector<std::string> * suggestions = manager.getAllNamesWithPrefix(currentInput);
            if (suggestions && suggestions->size() == 1) {
                 currentInput = suggestions->front();
                 std::cout << "\r" << currentInput << std::flush;  
            }
            delete suggestions;
        } else { 
            currentInput += c;
        }
    }
}

Here is a link to my GitHub Repo.

Hi! This is because you most probably run your shell through another shell (e.g. bash). To disable the input buffering feature in bash, you can:

2 Likes

Thank you maxim. :blush:
I otherwise would have searched a month for the bug in my code that was never in my code.
You seem to be using lots of design patterns. Any refactoring ideas for my shell-project?
Click Me

Thank you maxim. :blush:
Do you have any other advice or a refactoring idea for my project?

My biggest breakthough was when I realized that the “frontend” should be separated from the “backend” for this project (as always for any other project). More precisely, the logic related to printing to standard out and standard error should be separated from the core shell logic. On a side note: test driven development helped me to refactor the project multiply times while guideing the development along the way, highly recommend to learn this skill. Good luck on your endeavors!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.