0

If I hit the space bar then it should enter the loop and execute functionality... The below code is for enter. Please let me know how to do the same with space bar hit

#include <stdio.h>
int main()
{
  char ch;
  //infinite loop
  while(1)
  {
    printf("Enter any character: ");
    ch=fgetc(stdin);
    if(ch==0x0A)
    {
      printf("ENTER KEY is pressed.\n");
      break;
    }
    else
    {
      printf("%c is pressed.\n",ch);
    }
    ch=getchar();
  }
  return 0;
}
Ente
  • 2,301
  • 1
  • 16
  • 34
  • Just change to `if(ch==0x20)` (provided you have a terminal in character mode) – Ctx Feb 13 '20 at 23:50
  • You always need system calls to obtain a pressed key, even if they are hidden in library calls like `fgetc()`. If you don't use system calls, you will need to access the hardware directly, what you cannot do as a "normal" user on the desktop system you are using presumambly. – the busybee Feb 14 '20 at 07:23
  • You need to put the terminal in raw/non-cannonical mode [Capture characters from standard input without waiting for enter to be pressed](https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed/912796?r=SearchResults&s=18|45.6671#912796) – David C. Rankin Feb 14 '20 at 08:13

2 Answers2

0

Use spacebar ASCII hex value.

  if(ch==0x20)
  {
    printf("Space key is pressed.\n");
  }
ROOT
  • 11,363
  • 5
  • 30
  • 45
0

I think that what @Sreekar Sai is asking for is a way to read the space bar input without having to press the enter.

By default, the terminal will buffer all information until Enter is pressed, before even sending it to the C program.

This is called the canonical mode (https://www.gnu.org/software/libc/manual/html_node/Canonical-or-Not.html).

To solve this you need to disable the canonical mode, and run your application. Here is a link where they have discussed the same and provided the solution: How to avoid pressing enter with getchar()

Also remove the ch=getchar(); from the while loop, as I don't see the need of it.

There is also the possibility of using the conio.h header file and use the getch() function. I have not personally verified this, but you can give it a try.

kiranm
  • 11
  • 3