Press anykey to continue in Linux C++

后端 未结 3 1185
无人共我
无人共我 2021-01-15 16:42

I am not sure if being in linux makes any different, but i have found online that this:

    cout << \"Press Enter to Continue...\";
    cin.ignore(nume         


        
相关标签:
3条回答
  • 2021-01-15 17:05

    Couldn't you just use cin.get() (get one character)?

    0 讨论(0)
  • 2021-01-15 17:11

    Here is a snippet from my code. It works in both windows and linux.

    #include <iostream>
    
    using std::cout;
    using std::cin;
    
    // Clear and pause methods
    #ifdef _WIN32
    // For windows
    void clearConsole() {
        system("cls");
    }
    
    void waitForAnyKey() {
        system("pause");
    }
    #elif __linux__
    // For linux
    void clearConsole() {
        system("clear");
    }
    
    void waitForAnyKey() {
        cout << "Press any key to continue...";
        system("read -s -N 1"); // Continues when pressed a key like windows
    }
    
    #endif
    
    int main() {
        cout << "Hello World!\n";
        waitForAnyKey();
        clearConsole();
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-15 17:27

    In *nix, terminals usually wait for a whole line of input before sending anything to the program. Which is why the example code you posted said "Press Enter to Continue...";, and then discarded everything until the next newline.

    To avoid that, you should put your terminal in non-canonical mode, which can be done using the POSIX termios(3) functions, as explained in How to check if a key was pressed in Linux?.

    0 讨论(0)
提交回复
热议问题