gpt4 book ai didi

c++ - std::cin:清空输入缓冲区而不阻塞

转载 作者:太空宇宙 更新时间:2023-11-04 11:41:26 32 4
gpt4 key购买 nike

this 的跟进问题。

如何清除输入缓冲区?

sleep(2);
// clear cin
getchar();

我只想要最后输入的字符,我想丢弃程序休眠时输入的任何内容。有办法吗?

此外,我不想主动等待清除 cin,因此我不能使用 ignore()。

我的方法是获取缓冲区的当前大小,如果它不等于 0,则静默清空缓冲区。但是,我还没有找到获取缓冲区大小的方法。 std::cin.rdbuf()->in_avail() 总是为我返回 0。 peek() 也积极等待。

我不想使用 ncurses。

最佳答案

拥有一个支持 tcgetattr/tcsetattr 的系统:

#include <iostream>
#include <stdexcept>

#include <termios.h>
#include <unistd.h>

class StdInput
{
// Constants
// =========

public:
enum {
Blocking = 0x01,
Echo = 0x02
};

// Static
// ======

public:
static void clear() {
termios attributes = disable_attributes(Blocking);
while(std::cin)
std::cin.get();
std::cin.clear();
set(attributes);
}

// StdInput
// ========

public:
StdInput()
: m_restore(get())
{}

~StdInput()
{
set(m_restore, false);
}

void disable(unsigned flags) { disable_attributes(flags); }
void disable_blocking() { disable_attributes(Blocking); }
void restore() { set(m_restore); }

private:
static termios get() {
const int fd = fileno(stdin);
termios attributes;
if(tcgetattr(fd, &attributes) < 0) {
throw std::runtime_error("StdInput");
}
return attributes;
}

static void set(const termios& attributes, bool exception = true) {
const int fd = fileno(stdin);
if(tcsetattr(fd, TCSANOW, &attributes) < 0 && exception) {
throw std::runtime_error("StdInput");
}
}

static termios disable_attributes(unsigned flags) {
termios attributes = get();
termios a = attributes;
if(flags & Blocking) {
a.c_lflag &= ~ICANON;
a.c_cc[VMIN] = 0;
a.c_cc[VTIME] = 0;
}
if(flags & Echo) {
a.c_lflag &= ~ECHO;
}
set(a);
return attributes;
}

termios m_restore;
};


int main()
{
// Get something to ignore
std::cout << "Ignore: ";
std::cin.get();

// Do something

StdInput::clear();

std::cout << " Input: ";
std::string line;
std::getline(std::cin, line);
std::cout << "Output: " << line << std::endl;

return 0;
}

关于c++ - std::cin:清空输入缓冲区而不阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21233068/

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