Alex Rivera | Logout

How to read until ESC button is pressed from cin in C++

Asked 2013-01-08T12:16:09.193
8

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

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?

EDIT:

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:

Guys, this soulution doesn't work too, it eats the first char from my line!

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

1 Answer

1

After you read the line, go though all characters you just read and look for the escape ASCII value (decimal 27).


Here's what I mean:

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;
}
answered 2013-01-08T12:23:41.927

Your Answer