如何在C ++中从cin按下ESC按钮之前阅读

时间:2013-01-08 12:16:09

标签: c++ escaping getline

我正在编写一个直接从用户输入读取数据的程序,并想知道在按下键盘上的ESC按钮之前我怎样才能读取所有数据。我发现只有这样的东西:

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

但是需要添加一个可移植的方式(Linux / Windows)来捕获按下的ESC按钮然后打破while循环。怎么做?

编辑:

我写了这个,但仍然 - 即使我按下键盘上的ESC按钮也能正常工作:

#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;
}

5 个答案:

答案 0 :(得分:6)

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

 cout << str;

return 0;
}

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

答案 1 :(得分:1)

读完该行后,浏览刚读过的所有字符并查找转义ASCII值(十进制数27)。


这就是我的意思:

while (std::getline(std::cin, line) && moveOn)
{
    std::cout << line << "\n";

    // Do whatever processing you need

    // Check for ESC
    bool got_esc = false;
    for (const auto c : line)
    {
        if (c == 27)
        {
            got_esc = true;
            break;
        }
    }

    if (got_esc)
        break;
}

答案 2 :(得分:1)

我发现这适用于获取转义键的输入,您还可以在while函数中定义和列出其他值。

#include "stdafx.h"
#include <iostream>
#include <conio.h> 

#define ESCAPE 27

int main()
{
    while (1)
    {
        int c = 0;

        switch ((c = _getch()))
        {
        case ESCAPE:
            //insert action you what
            break;
        }
    }
    return 0;
}

答案 3 :(得分:0)

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
    int number;
    char ch;

    bool loop=false;
    while(loop==false)
    {  cin>>number;
       cout<<number;
       cout<<"press enter to continue, escape to end"<<endl;
       ch=getch();
       if(ch==27)
       loop=true;
    }
    cout<<"loop terminated"<<endl;
    return 0;
}

答案 4 :(得分:0)

我建议不仅仅是C ++中的ESC字符,而是任何语言中键盘的任何其他字符,请读取输入整数变量的字符,然后将它们打印为整数。

或者在线搜索ASCII字符列表。

这将为您提供键的ASCII值,然后它很简单

if(foo==ASCIIval)
   break;
  

对于ESC字符,ASCII值为27。