简体   繁体   中英

C++ - Pause program until a certain key is pressed

是否存在使命令提示符程序像system("pause")那样等待并仅在接受特定键后才能继续运行的功能?

If you're waiting for a newline character, there's an easy and portable way to do that. Just use getline .

If you want to receive other characters without receiving a newline first, then things are less portable. In Unix systems, you'll need to set your terminal to "raw mode". As George's comment mentions, ncurses is an easy way to do this, plus it provides handy functions for drawing things to a specific place in the terminal, receiving arbitrary keys, etc.

On Windows, you'll need to use its console interface . This is, of course, not usable outside of Windows.

As Neil Butterworth comments, there's also a version of curses that works for Windows, called PDCurses. If you need to write software that works for both Unix and Windows, that's a good option to pursue.

If getline and ncurses don't work for you there is always conio.h and getch(). There are some problems with this as explained in this answer Why can't I find <conio.h> on Linux?

Good luck.

在Windows控制台界面上, getche()函数将在进一步执行之前等待按键。

If you're on Windows, you can use kbhit() which is part of the Microsoft run-time library. If you're on Linux, you can implement kbhit thus

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

int kbhit(void)
{
  struct termios oldt, newt;
  int ch;
  int oldf;

  tcgetattr(STDIN_FILENO, &oldt);
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
  fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

  ch = getchar();

  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  fcntl(STDIN_FILENO, F_SETFL, oldf);

  if(ch != EOF)
  {
    ungetc(ch, stdin);
    return 1;
  }

  return 0;
}

Compiling steps :

 gcc -o kbhit kbhit.c

When run with

 ./kbhit

It prompts you for a keypress, and exits when you hit a key (not limited to Enter or printable keys).

(Got over internet - you can modify code and use specific ch value like \\n for Enter key)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM