Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

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

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 << "
";
        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 << "
";
        c = cin.get();
        if(c == ESC)
            break;

    }
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
int main() {
  string str = "";
  char ch;
  while ((ch = std::cin.get()) != 27) {
    str += ch;
  }

 cout << str;

return 0;
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...