gpt4 book ai didi

c++ - 在 C++ 中从 cin 按下 ESC 按钮之前如何读取

转载 作者:太空狗 更新时间:2023-10-29 20:05:18 26 4
gpt4 key购买 nike

我正在编写一个直接从用户输入中读取数据的程序,并且想知道在按下键盘上的 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;
}

编辑2:

伙计们,这个解决方案也不起作用,它吃掉了我行中的第一个字符!

#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 main() {
string str = "";
char ch;
while ((ch = std::cin.get()) != 27) {
str += ch;
}

cout << str;

return 0;
}

这会将输入输入到您的字符串中,直到遇到转义字符

关于c++ - 在 C++ 中从 cin 按下 ESC 按钮之前如何读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14214753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com