热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何模拟“按任意键继续?”-Howtosimulate“Pressanykeytocontinue?”

IamtryingtowriteaC++programinwhichwhenuserenteranycharacterfromkeyboardanditshoul

I am trying to write a C++ program in which when user enter any character from keyboard and it should move to next line of code.

我正在尝试编写一个c++程序,当用户从键盘输入任何字符时,它应该移动到下一行代码。

Here is my code:

这是我的代码:

char c;

cin>>c;

cout<<"Something"<

but this is not working, because it only move to next line when I input some character and then press ENTER.

但这行不通,因为它只会移动到下一行当我输入某个字符然后按ENTER。

OR

If I use this

如果我用这个

cin.get() or cin.get(c)

it move to next line of instruction when I press Enter.

当我按回车键时,它移动到下一行。

But I wanted it to move to next line on any key pressed on the keyboard, how this can be done?

但是我想让它移动到键盘上任何按键上的下一行,这是怎么做到的呢?

15 个解决方案

#1


50  

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 (source):

如果您在Windows上,可以使用kbhit(),它是Microsoft运行时库的一部分。如果您在Linux上,那么可以实现kbhit(源代码):

#include 
#include 
#include 
#include 

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

Update: The above function works on OS X (at least, on OS X 10.5.8 - Leopard, so I would expect it to work on more recent versions of OS X). This gist can be saved as kbhit.c and compiled on both Linux and OS X with

更新:上面的函数在OS X上工作(至少在OS X 10.5.8 - Leopard上,所以我希望它能在最近版本的OS X上运行)。并在Linux和OS X上编译。

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).

它提示您输入一个按键,当您点击一个键(不限于输入或可打印的键)时退出。

@Johnsyweb - please elaborate what you mean by "detailed canonical answer" and "all the concerns". Also, re "cross-platform": With this implementation of kbhit() you can have the same functionality in a C++ program on Linux/Unix/OS X/Windows - which other platforms might you be referring to?

@Johnsyweb -请详细说明你所说的“详细规范答案”和“所有关注事项”。另外,re“跨平台”:在kbhit()的实现中,您可以在Linux/Unix/OS X/Windows上的c++程序中拥有相同的功能——您可能指的是其他平台?

Further update for @Johnsyweb: C++ applications do not live in a hermetically sealed C++ environment. A big reason for C++'s success is interoperability with C. All mainstream platforms are implemented with C interfaces (even if internal implementation is using C++) so your talk of "legacy" seems out of place. Plus, as we are talking about a single function, why do you need C++ for this ("C with classes")? As I pointed out, you can write in C++ and access this functionality easily, and your application's users are unlikely to care how you implemented it.

@Johnsyweb的进一步更新:c++应用程序不存在于密封的c++环境中。c++成功的一个重要原因是与C的互操作性。所有主流平台都是用C接口实现的(即使内部实现使用c++),所以您的“遗留”话题似乎已经过时了。另外,当我们讨论一个函数时,为什么需要c++来实现这个(“C和类”)?正如我指出的那样,您可以在c++中编写并轻松地访问该功能,您的应用程序的用户不太可能关心您是如何实现它的。

#2


48  

On Windows:

在Windows上:

system("pause");

and on Mac and Linux:

在Mac和Linux上:

system("read");

will output "Press any key to continue..." and obviously, wait for any key to be pressed. I hope thats what you meant

将输出“按任意键继续…”,显然,等待任何键被按下。我希望你是这个意思。

#3


7  

There is no completely portable solution.

没有完全可移植的解决方案。

Question 19.1 of the comp.lang.c FAQ covers this in some depth, with solutions for Windows, Unix-like systems, and even MS-DOS and VMS.

问题19.1 .朗。c FAQ在一些深度上涵盖了这个问题,包括Windows、unix系统,甚至MS-DOS和vm的解决方案。

A quick and incomplete summary:

快速而不完整的摘要:

  • You can use the curses library; call cbreak() followed by getch() (not to be confused with the Windows-specific getch()function). Note that curses generally takes control of the terminal, so this is likely to be overkill.
  • 你可以使用curses库;调用cbreak()后跟getch()(不要与特定于windows的getch()函数混淆)。注意,curses通常控制终端,所以这可能是过量的。
  • You might be able to use ioctl() to manipulate the terminal settings.
  • 您可以使用ioctl()来操作终端设置。
  • On POSIX-compliant systems, tcgetattr() and tcsetattr() may be a better solution.
  • 在符合posix的系统中,tcgetattr()和tcsetattr()可能是更好的解决方案。
  • On Unix, you can use system() to invoke the stty command.
  • 在Unix上,可以使用system()来调用stty命令。
  • On MS-DOS, you can use getch() or getche().
  • 在MS-DOS上,您可以使用getch()或getche()。
  • On VMS (now called OpenVMS), the Screen Management (SMG$) routines might do the trick.
  • 在VMS(现在称为OpenVMS)上,屏幕管理(SMG$)例程可能会起作用。

All these C solutions should work equally well in C++; I don't know of any C++-specific solution.

所有这些C解决方案应该在c++中同样有效;我不知道有什么c++特定的解决方案。

#4


6  

To achieve this functionality you could use ncurses library which was implemented both on Windows and Linux (and MacOS as far as I know).

为了实现这个功能,您可以使用ncurses库,它在Windows和Linux上都实现了(据我所知是MacOS)。

#5


4  

I looked into what you are trying to achieve, because I remember I wanted to do the same thing. Inspired by Vinay I wrote something that works for me and I sort of understand. But I am not an expert, so please be careful.

我研究了你想要达到的目标,因为我记得我也想做同样的事情。受Vinay的启发,我写了一些对我有用的东西,我也能理解。但我不是专家,所以请小心。

I don't know how Vinay knows you are using Mac OS X. But it should work kind of like this with most unix-like OS. Really helpful as resource is opengroup.org

我不知道Vinay如何知道你在使用Mac OS x,但它应该是类似于大多数unix操作系统的。真正有用的资源是opengroup.org。

Make sure to flush the buffer before using the function.

在使用该函数之前,请确保刷新缓冲区。

#include 
#include         //termios, TCSANOW, ECHO, ICANON
#include      //STDIN_FILENO


void pressKey()
{
    //the struct termios stores all kinds of flags which can manipulate the I/O Interface
    //I have an old one to save the old settings and a new 
    static struct termios oldt, newt;
    printf("Press key to continue....\n");

    //tcgetattr gets the parameters of the current terminal
    //STDIN_FILENO will tell tcgetattr that it should write the settings
    // of stdin to oldt
    tcgetattr( STDIN_FILENO, &oldt);
    //now the settings will be copied 
    newt = oldt;

    //two of the c_lflag will be turned off
    //ECHO which is responsible for displaying the input of the user in the terminal
    //ICANON is the essential one! Normally this takes care that one line at a time will be processed
    //that means it will return if it sees a "\n" or an EOF or an EOL
    newt.c_lflag &= ~(ICANON | ECHO );      

    //Those new settings will be set to STDIN
    //TCSANOW tells tcsetattr to change attributes immediately. 
    tcsetattr( STDIN_FILENO, TCSANOW, &newt);

    //now the char wil be requested
    getchar();

    //the old settings will be written back to STDIN
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt);

}


int main(void)
{
  pressKey();
  printf("END\n");
  return 0;
}

O_NONBLOCK seems also to be an important flag, but it didn't change anything for me.

O_NONBLOCK似乎也是一个重要的标志,但它并没有改变我的任何东西。

I appreciate if people with some deeper knowledge would comment on this and give some advice.

如果有更深入的知识的人对此发表评论并给出一些建议,我将不胜感激。

#6


4  

You could use the Microsoft-specific function _getch:

你可以使用microsoftspecific function _getch:

#include 
#include 
// ...
// ...
// ...
cout <<"Press any key to continue..." <

#7


4  

This is very simple . I made a program and it works perfect..Here is the program.

这很简单。我做了一个程序,它很完美。这是程序。

#include
#include

void  check()
{
    char chk; int j;
    cout<<"\n\nPress any key to continue...";
    chk=getch();
    j=chk;
    for(int i=1;i<=256;i++)
      if(i==j) break;
    clrscr();
}

void main()
{
    clrscr();
    check();
    cout<<"\n\nSee, Its Working....Have a Good day";
    getch();
}

#8


3  

This works on a Windows Platform: It Uses the Microprocessor registers directly and can be used to check key press or mousebutton

这在Windows平台上运行:它直接使用微处理器寄存器,可以用来检查按键或鼠标按钮。

    #include
    #include
    #include
    void main()
    {
     clrscr();
     union REGS in,out;
     in.h.ah=0x00;
     printf("Press any key : ");

     int86(0x16,&in,&out);
     printf("Ascii : %d\n",out.h.al);
     char ch = out.h.al;
     printf("Charcter Pressed : %c",&ch);
     printf("Scan code : %d",out.h.ah);
     getch();
    }

#9


2  

If you're using Visual Studio 2012 or older, use the "getch()" function, if you are using Visual Studio 2013 or newer, use "_getch()". You will have to use "#include ". Example:

如果你使用的是Visual Studio 2012或更老的,使用“getch()”函数,如果你使用Visual Studio 2013或更新,使用“_getch()”。您必须使用“#include ”。例子:

#include "stdafx"
#include 
#include 

int main()
{
   std::cout <<"Press any key to continue. . .\n"
   _getch() //Or "getch()"
}

#10


1  

You can use the getchar routine.

可以使用getchar例程。

From the above link:

从上面的链接:

/* getchar example : typewriter */
#include 

int main ()
{
  char c;
  puts ("Enter text. Include a dot ('.') in a sentence to exit:");
  do {
    c=getchar();
    putchar (c);
  } while (c != '.');
  return 0;
}

#11


0  

Also you can use getch() from conio.h. Just like this:

您也可以使用来自conio.h的getch()。就像这样:

...includes, defines etc
void main()
{
//operator
getch(); //now this function is waiting for any key press. When you have pressed its     just     //finish and next line of code will be called
}

So, because UNIX does not have conio.h, we can simulate getch() by this code (but this code already written by Vinary, my fail):

因为UNIX没有conio。h,我们可以通过这个代码来模拟getch()(但是这个代码已经由Vinary编写,我的失败):

#include 
#include 
#include 

int mygetch( ) {
  struct termios oldt,
             newt;
  int            ch;
  tcgetattr( STDIN_FILENO, &oldt );
  newt = oldt;
  newt.c_lflag &= ~( ICANON | ECHO );
  tcsetattr( STDIN_FILENO, TCSANOW, &newt );
  ch = getchar();
  tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
  return ch;
}

#12


-1  

#include 
using namespace std;

int main () {
    bool boolean;
    boolean = true;

    if (boolean == true) {

        cout <<"press any key to continue";
        cin >> boolean;

    }
    return 0;
}

#13


-2  

If you look up kbhit() function on MSDN now, it says the function is deprecated. Use _kbhit() instead.

如果您现在在MSDN上查找kbhit()函数,它表示该函数已被弃用。使用_kbhit()。

#include 
int main()
{
    _kbhit();
    return 0;
}

#14


-2  

You can use Scanner variable, and use the HasNext() method. Then break it and exit using a function exit();

您可以使用扫描器变量,并使用HasNext()方法。然后使用函数exit()将其断开并退出;

import java.util.Scanner;

    public class exit_onClick {
        public static int exit()
        {
            return 0;
        }
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            System.out.println("Press Any Key to EXIT....");
            int c=0;
            while(scan.hasNext())
            {
                c++;
                if(c==1)
                    break;
            }
            exit();
        }

    }

#15


-4  

Just use the system("pause"); command.

只使用系统(“暂停”);命令。

All the other answers over complicate the issue.

所有其他的答案都把这个问题复杂化了。


推荐阅读
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • UNP 第9章:主机名与地址转换
    本章探讨了用于在主机名和数值地址之间进行转换的函数,如gethostbyname和gethostbyaddr。此外,还介绍了getservbyname和getservbyport函数,用于在服务器名和端口号之间进行转换。 ... [详细]
  • 本章将深入探讨移动 UI 设计的核心原则,帮助开发者构建简洁、高效且用户友好的界面。通过学习设计规则和用户体验优化技巧,您将能够创建出既美观又实用的移动应用。 ... [详细]
  • 本文介绍如何使用 Python 将一个字符串按照指定的行和元素分隔符进行两次拆分,最终将字符串转换为矩阵形式。通过两种不同的方法实现这一功能:一种是使用循环与 split() 方法,另一种是利用列表推导式。 ... [详细]
  • 本文详细探讨了KMP算法中next数组的构建及其应用,重点分析了未改良和改良后的next数组在字符串匹配中的作用。通过具体实例和代码实现,帮助读者更好地理解KMP算法的核心原理。 ... [详细]
  • Explore how Matterverse is redefining the metaverse experience, creating immersive and meaningful virtual environments that foster genuine connections and economic opportunities. ... [详细]
  • 题目描述:给定n个半开区间[a, b),要求使用两个互不重叠的记录器,求最多可以记录多少个区间。解决方案采用贪心算法,通过排序和遍历实现最优解。 ... [详细]
  • CentOS7源码编译安装MySQL5.6
    2019独角兽企业重金招聘Python工程师标准一、先在cmake官网下个最新的cmake源码包cmake官网:https:www.cmake.org如此时最新 ... [详细]
  • 前言--页数多了以后需要指定到某一页(只做了功能,样式没有细调)html ... [详细]
  • 本文深入探讨了 Java 中的 Serializable 接口,解释了其实现机制、用途及注意事项,帮助开发者更好地理解和使用序列化功能。 ... [详细]
  • XNA 3.0 游戏编程:从 XML 文件加载数据
    本文介绍如何在 XNA 3.0 游戏项目中从 XML 文件加载数据。我们将探讨如何将 XML 数据序列化为二进制文件,并通过内容管道加载到游戏中。此外,还会涉及自定义类型读取器和写入器的实现。 ... [详细]
  • 本文详细探讨了在Android 8.0设备上使用ChinaCock的TCCBarcodeScanner进行扫码时出现的应用闪退问题,并提供了解决方案。通过调整配置文件,可以有效避免这一问题。 ... [详细]
  • 本文详细解析了Python中的os和sys模块,介绍了它们的功能、常用方法及其在实际编程中的应用。 ... [详细]
  • 扫描线三巨头 hdu1928hdu 1255  hdu 1542 [POJ 1151]
    学习链接:http:blog.csdn.netlwt36articledetails48908031学习扫描线主要学习的是一种扫描的思想,后期可以求解很 ... [详细]
  • This document outlines the recommended naming conventions for HTML attributes in Fast Components, focusing on readability and consistency with existing standards. ... [详细]
author-avatar
泱泱大国吴
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有