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

前端 未结 5 1226
予麋鹿
予麋鹿 2020-12-10 19:17

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 li

相关标签:
5条回答
  • 2020-12-10 19:51
    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

    0 讨论(0)
  • 2020-12-10 19:54

    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;
    }
    
    0 讨论(0)
  • 2020-12-10 19:59

    I would suggest that for not just ESC character in C++, but for any other character of the keyboard in any language, read characters that you input into an integer variable and then print them as integer.

    Either that or search online for a list of the ASCII characters.

    This will give you ASCII value of the key, and then it's plain simple

    if(foo==ASCIIval)
       break;
    

    For the ESC character, the ASCII value is 27.

    0 讨论(0)
  • 2020-12-10 20:00

    I found that this works for getting input for the escape key, you can also define and list other values in the while function.

    #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;
    }
    
    0 讨论(0)
  • 2020-12-10 20:00
    #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;
    }
    
    0 讨论(0)
提交回复
热议问题