如何阅读,直到ESC按钮被从C ++中按下 [英] How to read until ESC button is pressed from cin in C++

查看:197
本文介绍了如何阅读,直到ESC按钮被从C ++中按下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写的程序直接从用户输入读取数据,并且想知道如何在按下键盘上的ESC按钮之前读取所有数据。我发现只有这样:

I'm coding a program that reads data directly from user input and was wondering how could I read all data until ESC button on keyboard is pressed. I found only something like this:

std::string line;
while (std::getline(std::cin, line))
{
    std::cout << line << std::endl;
}

但需要添加一个可移植的方式按钮,然后断开while循环。如何做到这一点?

but need to add a portable way (Linux/Windows) to catch a ESC button pressed and then break a while loop. How to do this?

编辑:

我键盘上的ESC按钮:

I wrote this, but still - works even if I press an ESC button on my keyboard:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    const int ESC=27;
    std::string line;
    bool moveOn = true;

    while (std::getline(std::cin, line) && moveOn)
    {
        std::cout << line << "\n";
        for(unsigned int i = 0; i < line.length(); i++)
        {
            if(line.at(i) == ESC)
            { 
                moveOn = false;
                break;

            }
        }
    }
    return 0;
}

EDIT2:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    const int ESC=27;
    char c;
    std::string line;
    bool moveOn = true;

    while (std::getline(std::cin, line) && moveOn)
    {
        std::cout << line << "\n";
        c = cin.get();
        if(c == ESC)
            break;

    }
    return 0;
}


推荐答案

int main() {
  string str = "";
  char ch;
  while ((ch = std::cin.get()) != 27) {
    str += ch;
  }

 cout << str;

return 0;
}

这会将输入传入您的字符串,直到遇到Escape字符

this takes the input into your string till it encounters Escape character

这篇关于如何阅读,直到ESC按钮被从C ++中按下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆