简体   繁体   中英

using enter to continue and esc to exit C++

I am new to this and trying to continue if enter is pressed and exit if esc is pressed. Really just asking for the knowledge down the road, and is not completely necessary for the program I am currently writing.

#include <iostream>
#include <iomanip>

void StartMessage(char cont)
{
    while (cont != 27)
    {
    std::cout << "> PROTOCOL: Overloaded Hospital\n"
        << "> Running. . .\n"
        << "> Hello\n"
        << "> Enter to Continue, Esc to exit";
    std::cin.get();
    }
}


int main()
{

//Variables
char cont = '0';

//Constants

StartMessage(cont);

return 0;
}

What do I need to do to get this to work properly as described above?

#include<Windows.h>
#include<iostream>

int main()
{
    while(true)
    {    // GetAsyncKeyState take virtual key code
         if(GetAsyncKeyState(VK_ESCAPE) {
             std::cout << "escape key pressed" <<endl;
         }
         if(GetAsyncKeyState(VK_ENTER) {
             std::cout << "enter key pressed" << endl;
         }
     }
}

Well, its not possible to check if a key is hit and continue if not. You need to wait until the user press enter and here in your code, you have an infinite loop, dont forget to update cont.

cont = std::cin.get();

As others have said, the terminal will wait for a full line of test to be entered, followed by a newline, so you can't really get this behavior with just C++, independent of platform. The terminal will also not accept a blank input with just a newline. If you want real-time input with C++, there are libraries you can look at (like SDL), but it probably isn't a good place to start for a beginner.

Something like this will give similar behavior to what you want:

#include <iostream>


void StartMessage()
{
    std::string s;
    do
    {
    std::cout << "> PROTOCOL: Overloaded Hospital\n"
        << "> Running. . .\n"
        << "> Hello\n"
        << "> Esc to exit";


    std::cin >> s;
    } while(s[0] != 27);
   std::cout << "\nExiting\n";
}


int main()
{



StartMessage();

return 0;
}

This will exit only if you enter a line starting with escape, but you have to hit enter after. It might be better to use a character like 'q' for this so it prints out more clearly on the terminal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM