Search code examples
c++ctrl

How to detect user input of CTRL-X in C++


I need to end my function once the user inputs CTRL-X or '/'. I don't know how to detect/check for a user input of CTRL-X. The task given to me states: 'When you edit the file, you will enter data line by line and when done, you will enter ‘/’ or CTRL + X to exit.'

I have written this code so far. I'm a beginner so pardon my code.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    string data;
    int line_num=1;
    ofstream editFile;
    editFile.open("edit_test.txt");

    while(data!="/"){ //some kind of condition ORed with the condition already present in while loop? 
        cout<<line_num<<"> "; //I want to display line numbers every time the user presses enter
        getline(cin, data);
        if(data!="/"){
            editFile<<data<<endl;
            line_num++;
        }
    }

    editFile.close();
    return 0;   
}

Solution

  • CTRL+X is the same as character code 24 (since X is the 24th letter of the alphabet). Barring any system interference*, all you need to do is check to see if character code 24 is in the input.

    while (getline( std::cin, s ))
    {
      // Find ^C in s
      auto n = s.find( '\x18' );
      if (n != s.npos) s = s.substr( 0, n );
    
      // process s normally here
    
      // If ^C was found in s, we're done reading input from user
      if (n != s.npos) break;
    }
    

    CTRL+X doesn’t tend to have any special system actions attached to it, so you shouldn’t have any problem getting it as input.