等待,直到用户按下进入C ++? [英] Wait until user presses enter in C++?
问题描述
waitForEnter() {
char enter;
do {
cin.get(enter);
} while ( enter != '\n' );
}
它工作,但不总是。
推荐答案
您可以使用 getline
以使程序等待任何换行结束的输入:
You can use getline
to make the program wait for any newline-terminated input:
#include <string>
#include <iostream>
#include <limits>
void wait_once()
{
std::string s;
std::getline(std::cin, s);
}
一般来说,您不能简单地清除整个输入缓冲区,这个调用总是会阻塞。如果您知道您要舍弃的上一个输入,可以添加 std :: cin.ignore(std :: numeric_limits< std :: streamsize> :: max ),<\\ c $ c> getline
上方的任何剩余字符,可以使用\但是,如果没有额外的输入开始,这将导致一个额外的暂停。
In general, you cannot simply "clear" the entire input buffer and ensure that this call will always block. If you know that there's previous input that you want to discard, you can add std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
above the getline
to gobble up any left-over characters. However, if there was no extra input to begin with, this will cause an additional pause.
如果你想控制台和键盘的完全控制,你可能需要查看平台特定的解决方案,例如, ncurses
的终端库。
If you want full control over the console and the keyboard, you may have to look at a platform-specific solution, for instance, a terminal library like ncurses
.
A select
在Posix系统上调用,可以告诉你从文件描述符读取是否会阻塞,所以你可以写如下的函数:
A select
call on a Posix system that can tell you if reading from a file descriptor would block, so there you could write the function as follows:
#include <sys/select.h>
void wait_clearall()
{
fd_set p;
FD_ZERO(&p);
FD_SET(0, &p);
timeval t;
t.tv_sec = t.tv_usec = 0;
int sr;
while ((sr = select(1, &p, NULL, NULL, &t)) > 0)
{
char buf[1000];
read(0, buf, 1000);
}
}
这篇关于等待,直到用户按下进入C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!