首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无需等待按enter键即可从标准输入中捕获字符

无需等待按enter键即可从标准输入中捕获字符
EN

Stack Overflow用户
提问于 2009-01-08 04:04:17
回答 15查看 246.4K关注 0票数 211

我永远记不住我是如何做到这一点的,因为它对我来说是非常罕见的。但在C或C++中,从标准输入中读取字符而不等待换行符(按enter)的最佳方法是什么?

同样,理想情况下,它不会将输入字符回显到屏幕上。我只想在不影响控制台屏幕的情况下捕获击键。

EN

回答 15

Stack Overflow用户

发布于 2009-05-26 21:14:31

在Linux (和其他类unix系统)上,这可以通过以下方式完成:

代码语言:javascript
复制
#include <unistd.h>
#include <termios.h>

char getch() {
        char buf = 0;
        struct termios old = {0};
        if (tcgetattr(0, &old) < 0)
                perror("tcsetattr()");
        old.c_lflag &= ~ICANON;
        old.c_lflag &= ~ECHO;
        old.c_cc[VMIN] = 1;
        old.c_cc[VTIME] = 0;
        if (tcsetattr(0, TCSANOW, &old) < 0)
                perror("tcsetattr ICANON");
        if (read(0, &buf, 1) < 0)
                perror ("read()");
        old.c_lflag |= ICANON;
        old.c_lflag |= ECHO;
        if (tcsetattr(0, TCSADRAIN, &old) < 0)
                perror ("tcsetattr ~ICANON");
        return (buf);
}

基本上,您必须关闭规范模式(和回显模式以抑制回显)。

票数 97
EN

Stack Overflow用户

发布于 2009-05-26 19:07:25

我在另一个论坛上发现了这一点,同时希望解决同样的问题。我在我发现的基础上对它做了一些修改。它工作得很好。我运行的是OS,所以如果你运行的是Microsoft,你需要找到正确的system()命令来切换到raw和cooked模式。

代码语言:javascript
复制
#include <iostream> 
#include <stdio.h>  
using namespace std;  

int main() { 
  // Output prompt 
  cout << "Press any key to continue..." << endl; 

  // Set terminal to raw mode 
  system("stty raw"); 

  // Wait for single character 
  char input = getchar(); 

  // Echo input:
  cout << "--" << input << "--";

  // Reset terminal to normal "cooked" mode 
  system("stty cooked"); 

  // And we're out of here 
  return 0; 
}
票数 26
EN

Stack Overflow用户

发布于 2009-01-07 21:37:10

CONIO.H

您需要的函数包括:

代码语言:javascript
复制
int getch();
Prototype
    int _getch(void); 
Description
    _getch obtains a character  from stdin. Input is unbuffered, and this
    routine  will  return as  soon as  a character is  available  without 
    waiting for a carriage return. The character is not echoed to stdout.
    _getch bypasses the normal buffering done by getchar and getc. ungetc 
    cannot be used with _getch. 
Synonym
    Function: getch 


int kbhit();
Description
    Checks if a keyboard key has been pressed but not yet read. 
Return Value
    Returns a non-zero value if a key was pressed. Otherwise, returns 0.

libconio http://sourceforge.net/projects/libconio

conio.h http://sourceforge.net/projects/linux-conioh的Linux c++实现

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

https://stackoverflow.com/questions/421860

复制
相关文章

相似问题

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