2013-01-08 325 views
3

我正在编写一个程序,直接从用户输入读取数据,并想知道如何才能读取所有数据,直到键盘上的ESC按钮被按下。我发现只是这样的:如何阅读,直到从CIN按下ESC按钮C++

std::string line; 
while (std::getline(std::cin, line)) 
{ 
    std::cout << line << std::endl; 
} 

但需要添加一个便携的方式(Linux/Windows)来捕获一个ESC按钮,然后打破一个while循环。这个怎么做?

编辑:

我写了这一点,但仍然 - 即使我按下键盘上的ESC的按钮的工作原理:

#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 << "\n"; 
     for(unsigned int i = 0; i < line.length(); i++) 
     { 
      if(line.at(i) == ESC) 
      { 
       moveOn = false; 
       break; 

      } 
     } 
    } 
    return 0; 
} 

EDIT2:

家伙,这soulution不起作用它也会吃掉我的第一个字符!

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

    } 
    return 0; 
} 
+0

您可以设置'常量int ESC = 27;',然后在循环中使用'c = getch()',然后检查'c'是否等于'ESC'终止。 – Maroun

+0

@MarounMaroun:不是getch();只有Windows解决方案...? – Katie

+0

使用cin.get()而不是getch() – abnvp

回答

6
int main() { 
    string str = ""; 
    char ch; 
    while ((ch = std::cin.get()) != 27) { 
    str += ch; 
    } 

cout << str; 

return 0; 
} 

这需要输入到您的字符串,直到它遇到转义字符

1

在阅读的路线,虽然走的所有字符你刚才读,寻找逃逸ASCII值(十进制27)。


这里就是我的意思是:

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

的确如你所说,你能否看到我的编辑并说出它是否适合你?欢呼声:) – Katie

+0

@Katie:你应该每次使用cin.get()时都会得到一个字符,只要你看到ESC – abnvp

+1

@Katie就会中断。不,我的意思是你应该迭代字符串'line'。 _或__使用'std :: cin.get()'一次读取一个字符。 –

1

我发现,这个工程让输入Escape键,您还可以在while函数中定义和列出其他值。

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

我建议在C不仅是ESC字符++,但对键盘在任何语言的任何其他字符,读取的字符,你输入一个整型变量,然后打印出来的整数。

无论是在线搜索还是在线搜索ASCII字符列表。

这会给关键的你ASCII值,那么它的朴素简单

if(foo==ASCIIval) 
    break; 

对于ESC字符,ASCII值是27