Wait until user presses enter in C++?

倾然丶 夕夏残阳落幕 提交于 2019-12-18 09:09:43

问题


waitForEnter() {
    char enter;

    do {
        cin.get(enter);
    } while ( enter != '\n' );
}

It works, but not always. It doesn't work when an enter is pressed just before the function is called.


回答1:


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);
}

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.

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 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);
  }
}



回答2:


On Windows, you can do this:

void WaitForEnter()
{
    // if enter is already pressed, wait for
    // it to be released
    while (GetAsyncKeyState(VK_RETURN) & 0x8000) {}

    // wait for enter to be pressed
    while (!(GetAsyncKeyState(VK_RETURN) & 0x8000)) {}
}

I don't know the equivalent on Linux.




回答3:


(the first parameter) The name of the array of type char[] in which the characters read from cin are to be stored.

(the second parameter) The maximum number of characters to be read. When the specified maximum has been read, input stops.

(the third parameter) The character that is to stop the input process. You can specify any character here, and the first occurrence of that character will stop the input process.

cin.getline( name , MAX, ‘\n’ );

Page 175 IVOR HORTON’S BEGINNING VISUAL C++® 2010



来源:https://stackoverflow.com/questions/8177344/wait-until-user-presses-enter-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!