2017-09-03 93 views
0

我需要在用户输入CTRL - X或'/'时结束我的功能。我不知道如何检测/检查用户输入为CTRL - X。 给我的任务规定: “当你编辑文件,你会被行输入数据线,完成后,你将进入‘/’或CTRL +X退出。”如何在C++中检测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; 
} 
+0

https://stackoverflow.com/questions/1118957/c-how-to-simulate-an-eof – wally

+0

针对Windows的'GetAsyncKeystate',针对OSX的'CGEventSourceFlagsState'。至于Linux,我认为XInput或NCurses库可能会这样做。如果您希望我们提供帮助,您确实应该发布确切的家庭作业要求..我们无法给您一个确切的答案,因为这是作业,但我们仍然可以提供帮助。我们不知道你究竟在问什么。这对于一个学校任务来说听起来不太合适。 – Brandon

+0

@DúthomhasOoops,对不起。当然,我的意思是ncurses。 :-P ... – user0042

回答

0

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不倾向于连有任何特殊的系统行为,所以你不应该得到它作为输入的任何问题。