而用C读取字符打印 [英] Printing while reading characters in C

查看:115
本文介绍了而用C读取字符打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写code的一个简单的小片段向方向键preSS回应。
我知道了重新由^ [[A psented $ P $,我有以下的code,检查该序列:

I'm trying to write a simple little snippet of code to respond to an arrow key press. I know that up is represented by ^[[A, and I have the following code that checks for that sequence:

     while( 1 )
     {
         input_char = fgetc( stdin );

         if( input_char == EOF || input_char == '\n' )
         {
             break;
         }

         /* Escape sequence */
         if( input_char == 27 )
         {
             input_char = getc( stdin );

             if( input_char == '[' )
             {
                 switch( getc( stdin ) )
                 {
                     case 'A':
                     printf("Move up\n");
                     break;
                 }
             }
         }
     }

每当我打向上,转义序列(^ [[A)显示在屏幕上,但上移没有出现,直到我按下回车键。

Whenever I hit "up", the escape sequence (^[[A) shows up on the screen, but "Move up" doesn't appear until I hit enter.

的最终目标是,以取代一些其他数据的当前行的文本,所以我试图做

The end goal is to replace the text on the current line with some other data, and so I tried to do

printf("\r%s", "New Text");

代替上移,但它仍然没有露面,直到进入后是pressed。

in place of "Move up", but it still doesn't show up until after enter is pressed.

时有什么错,我读字符的方式?

Is there something wrong with the way I'm reading in characters?

谢谢!

修改的快速笔记,这​​对* nix系统。

EDIT Quick note, it's for *nix systems.

SOLUTION
感谢大家的指针。我stepanbujnak的解决方案了,因为它是非常简单。有一件事我注意到的是,有很多修改字符串(退格等)键的行为是不同的比你期望的那样。它将通过就行了(包括printf'd东西)任何东西退格,我不得不考虑到这一点。之后,它不是太坏得到休息加入行列:)

SOLUTION Thanks for the pointers everyone. I went with stepanbujnak's solution because it was rather straightforward. The one thing I noticed is that a lot of the behavior of keys that modify the string ( backspace, etc ) is different than you would expect. It will backspace through ANYTHING on the line (including printf'd stuff), and I had to account for that. After that it wasn't too bad getting the rest to fall in line :)

推荐答案

您实际上只需要使用禁用行缓冲的的termios

You actually only need to disable line buffering using termios

下面是这样做的例子:

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

int main() {
  struct termios old_term, new_term;
  char c;

  /* Get old terminal settings for further restoration */
  tcgetattr(0, &old_term);

  /* Copy the settings to the new value */
  new_term = old_term;

  /* Disable echo of the character and line buffering */
  new_term.c_lflag &= (~ICANON & ~ECHO);
  /* Set new settings to the terminal */
  tcsetattr(0, TCSANOW, &new_term);

  while ((c = getchar()) != 'q') {
    printf("You pressed: %c\n", c);
  }

  /* Restore old settings */
  tcsetattr(0, TCSANOW, &old_term);

  return 0;
}

这篇关于而用C读取字符打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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