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;
}
}
}
}
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");
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?
Thanks!
EDIT Quick note, it's for *nix systems.
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 :)