Press Enter to Continue

前端 未结 7 1867
南笙
南笙 2020-12-05 02:08

This doesn\'t work:

string temp;
cout << \"Press Enter to Continue\";
cin >> temp;
相关标签:
7条回答
  • 2020-12-05 02:35

    You need to include conio.h so try this, it's easy.

    #include <iostream>
    #include <conio.h>
    
    int main() {
    
      //some code like
      cout << "Press Enter to Continue";
      getch();
    
      return 0;
    }
    

    With that you don't need a string or an int for this just getch();

    0 讨论(0)
  • 2020-12-05 02:39

    The function std::getline (already introduced with C++98) provides a portable way to implement this:

    #include <iostream>
    #include <string>
    
    void press_any_key()
    {
        std::cout << "Press Enter to Continue";
        std::string temp;
        std::getline(std::cin, temp);
    }
    

    I found this thanks to this question and answer after I observed that std::cin >> temp; does not return with empty input. So I was wondering how to deal with optional user input (which makes sense for a string variable can of course be empty).

    0 讨论(0)
  • 2020-12-05 02:41

    Yet another solution, but for C. Requires Linux.

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void) {
        printf("Press any key to continue...");
        system("/bin/stty raw"); //No Enter
        getchar();
        system("/bin/stty cooked"); //Yes Enter
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-05 02:44

    Try:

    char temp;
    cin.get(temp);
    

    or, better yet:

    char temp = 'x';
    while (temp != '\n')
        cin.get(temp);
    

    I think the string input will wait until you enter real characters, not just a newline.

    0 讨论(0)
  • 2020-12-05 02:46
    cout << "Press Enter to Continue";
    cin.ignore();
    

    or, better:

    #include <limits>
    cout << "Press Enter to Continue";
    cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
    
    0 讨论(0)
  • 2020-12-05 02:50

    Replace your cin >> temp with:

    temp = cin.get();
    

    http://www.cplusplus.com/reference/iostream/istream/get/

    cin >> will wait for the EndOfFile. By default, cin will have the skipws flag set, which means it 'skips over' any whitespace before it is extracted and put into your string.

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