mercredi 28 avril 2021

C++ how to skip getline()?

I wrote the following simple C++11 program:

#include <iostream>
#include <signal.h>

void ctrlZHandler(int sig_num) {
    //SIGTSTP-18
    std::cout << "smash: got ctrl-Z" << std::endl;
}

int main(int argc, char *argv[]) {
    if (signal(SIGTSTP, ctrlZHandler) == SIG_ERR) {
        perror("smash error: failed to set ctrl-Z handler");
    }

    while (true) {
        std::cout << "my_bash> ";
        std::string cmd_line;
        std::getline(std::cin, cmd_line);
    }
    return 0;
}

it runs perfect when the user types something and presses enter, but when my program is waiting for input like this:

my_bash>

and then he presses ctrl+z I get:

my_bash> ^Zsmash: got ctrl-Z     
//Empty line here

How can I fix this?

I want something like normal terminal which is the following output:

my_bash> ^Zsmash: got ctrl-Z     
my_bash> 

In other words how can I tell getline to not-wait and go for next iteration?

Aucun commentaire:

Enregistrer un commentaire