【问题标题】:How to detect user input of CTRL-X in C++如何在 C++ 中检测用户输入的 CTRL-X
【发布时间】:2017-09-03 21:02:59
【问题描述】:

一旦用户输入 CTRL-X 或“/”,我需要结束我的函数。我不知道如何检测/检查 CTRL-X 的用户输入。 给我的任务是: '当你编辑文件时,你将逐行输入数据,完成后,你将输入'/'或CTRL + X退出。'

到目前为止,我已经编写了这段代码。我是初学者,请原谅我的代码。

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

【问题讨论】:

  • GetAsyncKeystate 用于 Windows,CGEventSourceFlagsState 用于 OSX。至于 Linux,我认为 XInput 或 NCurses 库可能会做到这一点。如果您希望我们提供帮助,您真的应该发布确切的作业要求。我们无法给您确切的答案,因为这是作业,但我们仍然可以提供帮助。我们不知道你到底在问什么……这听起来不适合学校作业。
  • @Dúthomhas 哎呀,对不起。我的意思当然是 ncurses。 :-P ...
  • 您是否误解了您的作业? Ctrl+X 是退出编辑器的一种方式,您可能会使用它来创建文件。 读取用 C++ 的文件是另一回事。
  • @Dúthomhas 我在 Windows 机器上使用 Code::blocks。 ctrl-x 不退出编辑器,而是显示“^X”。我很确定我没有误解分配,我只想在用户按下 ctrl-x 后退出我的 while 循环。

标签: c++ ctrl


【解决方案1】:

CTRL+X 与字符代码 24 相同(因为 X 是字母表的第 24 个字母)。除非有任何系统干扰*,否则您需要做的就是检查输入中是否有字符代码 24。

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 不会附加任何特殊的系统操作,因此将其作为输入应该不会有任何问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多