首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何模拟“按任意键继续?”

如何模拟“按任意键继续?”
EN

Stack Overflow用户
提问于 2009-09-19 19:35:50
回答 12查看 164.2K关注 0票数 94

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

下面是我的代码:

char c;

cin>>c;

cout<<"Something"<<endl;

但这是行不通的,因为它只在我输入字符然后按ENTER键时才移动到下一行。

如果我用这个

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

当我按Enter键时,它将移动到下一行指令。

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

EN

回答 12

Stack Overflow用户

发布于 2009-09-21 03:02:39

在Windows上:

system("pause");

在Mac和Linux上:

system("read");

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

票数 70
EN

Stack Overflow用户

发布于 2009-09-19 19:45:23

要实现这个功能,你可以使用ncurses库,这个库在Windows和Linux上都实现了(据我所知,还有MacOS )。

票数 5
EN

Stack Overflow用户

发布于 2009-09-20 01:17:35

我调查了你想要实现的目标,因为我记得我也想做同样的事情。受Vinay的启发,我写了一些适合我的东西,我有点理解。但是我不是专家,所以请小心。

我不知道Vinay是怎么知道你在使用most的,但它在大多数类unix操作系统上应该是这样工作的。因为资源是opengroup.org,所以非常有用

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

#include <stdio.h>
#include <termios.h>        //termios, TCSANOW, ECHO, ICANON
#include <unistd.h>     //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似乎也是一个重要的标志,但它并没有改变我的任何事情。

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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1449324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档