0

Was wondering how you would be able to test the input that is saved in an char array like...

   char input[INPUT_SIZE];

And using

fgets(input,INPUT_SIZE,stdin);

To get the input from the user but was wondering how i could use a if statement to test if the users input has been for example ctrl + d or any ctrl + anykey?

I tryed using there ascci value like this.. is an example to test for ctrl d

  if(result = 'EOT') {printf("EOT");}

Result is a char array aswell.

Mwiza
  • 7,780
  • 3
  • 46
  • 42
Lemex
  • 3,772
  • 14
  • 53
  • 87
  • You're thinking along the right lines, but `'EOT'` is not the ASCII value of Ctrl-D (you're looking for 4). Your example won't compile, or at the very least give a warning. – Mr Lister Mar 01 '12 at 11:16
  • so should i test it for result = 4? – Lemex Mar 01 '12 at 11:18
  • 2
    The line `if(result = 'EOT')` is wrong in so many ways in C. – AusCBloke Mar 01 '12 at 11:22
  • How would you rephrase it then? – Lemex Mar 01 '12 at 11:25
  • `=` is an assignment operator, not a comparison operator, and `'EOT'` is not a `char`. Also read the documentation for `fgets` to see what exactly it stores in the buffer and when it stops reading. The ASCII value for EOT is 4, try and run [this code](http://ideone.com/46ltl) and see if 4 comes up in the output. – AusCBloke Mar 01 '12 at 11:28

1 Answers1

1

You can only test Ctrl+d as your read returning EOF, see the manual of your read to have more info on this, but generally it returns 0. Same goes for Ctrl+c, as both are sending signals to your program.

For other Ctrl+key combinations, it highly depends on your system.

On linux Ctrl+a and Ctrl+e in a shell or emacs will move you to the beginning or the end / beginning of the line respectively.

The easiest to get what you want is to write a small program using read, unbuffered (see ioctl), with a 8-bytes buffer, and dump your read bytes each time you exit the read.

int nbr;
int i;
char buf[8];

nbr = 42;
while (nbr > 0)
{
  nbr = read(0, buf, 8);
  i = 0;
  while (i < nbr)
    printf("%x ", buf[i++]);
  printf("\n");
}

You will have the hex version of the ctrl+key received sequences. Likely to begin with \ESC or \033 (the escape character sequence). For example the arrow-up key looks like \033[A

Mwiza
  • 7,780
  • 3
  • 46
  • 42
Eregrith
  • 4,263
  • 18
  • 39