简体   繁体   English

使用 enter 继续和 esc 退出 C++

[英]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.我是新手,如果按下 enter 则尝试继续,如果按下 esc 则退出。 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。

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.正如其他人所说,终端将等待输入完整的测试行,然后输入换行符,因此您无法仅使用独立于平台的 C++ 真正获得此行为。 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.如果您想使用 C++ 进行实时输入,可以查看一些库(如 SDL),但对于初学者来说,这可能不是一个好的起点。

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.仅当您输入以 escape 开头的行时才会退出,但您必须在之后按 enter。 It might be better to use a character like 'q' for this so it prints out more clearly on the terminal.最好使用像 'q' 这样的字符,以便在终端上更清楚地打印出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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