View Single Post
  #1 (permalink)  
Old May 10th, 2006, 10:55 PM
Alan-LB Alan-LB is offline
Authorized User
 
Join Date: Mar 2005
Posts: 58
Thanks: 0
Thanked 1 Time in 1 Post
Send a message via MSN to Alan-LB Send a message via Yahoo to Alan-LB
Default getchar() problem

I am using Standard C compiled with GCC under Linux Fedora Core 4

When I run this program and enter a character at the prompt, I have to press the ENTER key as well. This gives me 2 input characters - 'a' and '\n' (Hex 61 and 0a)

It seems as though the getchar() function needs ENTER to terminate reading stdin.

I am trying to get the program to respond when I press one key only (ie without needing to press ENTER as well).

Program
~~~~~~~
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char x; //Input character
    while (1)
    {
        printf(">"); //Print prompt '>'
        x = getchar(); //Get input character
        printf("%d %02x \n", x, x);//Print character in decimal & Hex
        if (x == 'q') //Exit if the character is 'q'
            exit(0);
    }
}

Output
~~~~~
a < input character
>97 61
>10 0a
b < input character
>98 62
>10 0a
c < input character
>99 63
>10 0a
d < input character
>100 64
>10 0a
q < input character
>113 71

I have tried using scanf() but got the same results.

Any ideas as to how I can input ONE character only? TIA :)

Alan



Reply With Quote