如何避免使用 getchar() 按 Enter 键仅读取单个字符? [英] How to avoid pressing Enter with getchar() for reading a single character only?

查看:28
本文介绍了如何避免使用 getchar() 按 Enter 键仅读取单个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下一个代码中:

#include <stdio.h>

int main(void) {   
  int c;   
  while ((c=getchar())!= EOF)      
    putchar(c); 
  return 0;
}

我必须按 Enter 打印我用 getchar 输入的所有字母,但我不想这样做,我想做的是按信,并立即看到我介绍的字母重复而无需按 Enter.例如,如果我按下字母a",我想在它旁边看到另一个a",依此类推:

I have to press Enter to print all the letters I entered with getchar, but I don't want to do this, what I want to do is to press the letter and immediately see the the letter I introduced repeated without pressing Enter. For example, if I press the letter 'a' I want to see an other 'a' next to it, and so on:

aabbccddeeff.....

但是当我按'a'时什么也没有发生,我可以写其他字母并且只有当我按Enter时才会出现副本:

But when I press 'a' nothing happens, I can write other letters and the copy appears only when I press Enter:

abcdef
abcdef

我该怎么做?

我在Ubuntu下使用命令cc -o example example.c进行编译.

I am using the command cc -o example example.c under Ubuntu for compiling.

推荐答案

在 linux 系统上,您可以使用 stty 命令修改终端行为.默认情况下,终端会缓存所有信息,直到按下 Enter,甚至在将其发送到 C 程序之前.

On a linux system, you can modify terminal behaviour using the stty command. By default, the terminal will buffer all information until Enter is pressed, before even sending it to the C program.

一个快速、肮脏且不是特别便携的示例,用于从程序本身内部更改行为:

A quick, dirty, and not-particularly-portable example to change the behaviour from within the program itself:

#include<stdio.h>
#include<stdlib.h>

int main(void){
  int c;
  /* use system call to make terminal send all keystrokes directly to stdin */
  system ("/bin/stty raw");
  while((c=getchar())!= '.') {
    /* type a period to break out of the loop, since CTRL-D won't work raw */
    putchar(c);
  }
  /* use system call to set terminal behaviour to more normal behaviour */
  system ("/bin/stty cooked");
  return 0;
}

请注意,这并不是真正的最佳选择,因为它只是假设 stty 煮熟 是程序退出时您想要的行为,而不是检查原始终端设置是什么.此外,由于在原始模式下会跳过所有特殊处理,因此许多键序列(例如 CTRL-CCTRL-D)实际上不会像您期望的那样工作无需在程序中显式处理它们.

Please note that this isn't really optimal, since it just sort of assumes that stty cooked is the behaviour you want when the program exits, rather than checking what the original terminal settings were. Also, since all special processing is skipped in raw mode, many key sequences (such as CTRL-C or CTRL-D) won't actually work as you expect them to without explicitly processing them in the program.

您可以 man stty 以更好地控制终端行为,具体取决于您想要实现的目标.

You can man stty for more control over the terminal behaviour, depending exactly on what you want to achieve.

这篇关于如何避免使用 getchar() 按 Enter 键仅读取单个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆