如何避免preSS任何的getchar输入() [英] How to avoid press enter with any getchar()

查看:161
本文介绍了如何避免preSS任何的getchar输入()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是C编程语言中的诺瓦的问题:

This is a "novato" question for the C programming language:

在接下来的code:

#include<stdio.h>

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

我要preSS <大骨节病>输入打印我的getchar 输入的所有信件,但我并不想这样做, ,我想要做的是preSS信并立即看到我公司推出无需重复pressing <大骨节病>输入信。例如,如果我preSS字母'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.....

但是,当我preSS'一'什么也没发生,我可以写其他的字母和副本只有当我preSS <大骨节病>输入出现:

abcdef
abcdef

我怎样才能做到这一点?

How can I do this?

我使用Ubuntu下的命令 CC -o例如example.c 编译。

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

推荐答案

在Linux系统中,您使用的stty 命令可以修改终端的行为。默认情况下,终端将缓冲所有信息,直到<大骨节病>输入是pressed,甚至之前发送到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>

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-C CTRL-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.

您可以男人的stty 用于在终端的行为更多的控制权,恰恰取决于你想要达到什么目的。

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

这篇关于如何避免preSS任何的getchar输入()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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