【发布时间】:2012-12-22 07:00:48
【问题描述】:
我正在编写一个直接从用户输入读取数据的程序,我想知道在按下键盘上的 ESC 按钮之前如何读取所有数据。我发现只有这样的东西:
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:
伙计们,这个解决方案也不起作用,它吃掉了我的第一个字符!
#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;
}
【问题讨论】:
-
你可以设置一个
const int ESC=27;,然后在你的循环中使用c=getch(),然后检查c是否等于ESC来终止。 -
@MarounMaroun: 不是 getch();只有 Windows 解决方案...?
-
使用 cin.get() 代替 getch()
-
@abhinav:不起作用,请参阅我的编辑
-
@Katie:只要把角色放回行中。