我正在编写一个程序,直接从用户输入读取数据,并想知道如何才能读取所有数据,直到键盘上的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;
}
您可以设置'常量int ESC = 27;',然后在循环中使用'c = getch()',然后检查'c'是否等于'ESC'终止。 – Maroun
@MarounMaroun:不是getch();只有Windows解决方案...? – Katie
使用cin.get()而不是getch() – abnvp