473,503 Members | 2,029 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 6110 0a
b < input character 98 6210 0a
c < input character 99 6310 0a
d < input character 100 6410 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
May 11 '06 #1
6 5255
Alan wrote:

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


Search the net for kbhit.c there's a version of it out there for linux, i
use it a lot and it solves these kinds of problems. Just add the kbhit.c
file to your Makefile and put #include "kbhit.h" in your program.
Call init_keyboard() at top of program and close_keyboard() on or before
exit. These two steps are really important, dont forget them.
Warning: failure to call close_keyboard() before your program exits will
leave your keybaord in a really weird state.

Ah hell, its short enough - Here...
Eric

/* The following code is kbhit.c */
#include "kbhit.h"
#include <termios.h>
#include <unistd.h> // for read()

static struct termios initial_settings, new_settings;
static int peek_character = -1;

void init_keyboard()
{
tcgetattr(0,&initial_settings);
new_settings = initial_settings;
new_settings.c_lflag &= ~ICANON;
new_settings.c_lflag &= ~ECHO;
new_settings.c_lflag &= ~ISIG;
new_settings.c_cc[VMIN] = 1;
new_settings.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &new_settings);
}

void close_keyboard()
{
tcsetattr(0, TCSANOW, &initial_settings);
}

int kbhit()
{
unsigned char ch;
int nread;

if (peek_character != -1) return 1;
new_settings.c_cc[VMIN]=0;
tcsetattr(0, TCSANOW, &new_settings);
nread = read(0,&ch,1);
new_settings.c_cc[VMIN]=1;
tcsetattr(0, TCSANOW, &new_settings);
if(nread == 1)
{
peek_character = ch;
return 1;
}
return 0;
}

int readch()
{
char ch;

if(peek_character != -1)
{
ch = peek_character;
peek_character = -1;
return ch;
}
read(0,&ch,1);
return ch;
}
/*
kbhit.c EOF
*/
/* The following code is kbhit.h */
#ifndef __KBHIT_H__
#define __KBHIT_H__
void init_keyboard(void);
void close_keyboard(void);
int kbhit(void);
int readch(void);
#endif

/*
kbhit.h EOF
*/

/*
Use it like this quick and dirty example
*/
#include <stdlib.h>
#include <stdio.h>
#include "kbhit.h"
int main(void)
{
int ch;

init_keyboard(); // run this once per program

// one way to use it
if(kbhit()) ch = readch();

// here's another sample usage
do {
if(kbhit()) // kbhit returns immediately, key pressed or not
{
ch = readch();
// do whatever here based on value of ch
if(ch='q') break;
}
sleep(1);
} while(1);

close_keyboard();

return 0;
}
May 11 '06 #2
Eric wrote:
Alan wrote:
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()
If a function does not take parameters it is better to be explicit about it.
int main(void)
{
char x; //Input character
while (1)
{
printf(">"); //Print prompt '>'
You should flush stdout here your your prompt might not be displayed.
x = getchar(); //Get input character
getchar can return EOF indicating end-of-file or error. Most systems
have a way for the user to signal end-of-file from the keyboard, so even
if your program is only used interactively this can still happen. Get
the result in to a variable of type int (not char) and test for EOF.
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


Search the net for kbhit.c there's a version of it out there for linux, i
use it a lot and it solves these kinds of problems. Just add the kbhit.c


<snip>

Note that kbhit is non-standard and non-portable and any possible
implementation of it is not portable. If you want to discus how it can
be done please take it to an appropriate system specific group.

The reason that getchar works like it does is that input from stdin is
normally line buffered (i.e. input is loaded in to a buffer until there
is a complete line and only then made available to the program).

Also, what do you want to happen if the user redirects input to coming
from a file? Or pipes in the output of another program? Using the kbhit
solution suggested by Eric would probably be a problem then.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
May 11 '06 #3
Alan wrote:

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).


Just think about things for a moment. In general, you want to be
able to type, and correct, input on the fly. This means using
things like the backspace key. You want this editing to be done up
front, between the keyboard and your program. This means there has
to be a means of signalling "Editing done, use this". That is the
ENTER key, better known to us old fogies as 'return'.

Now think about how this is actually done, and you will see where
the term 'buffered input' comes from.

Some systems make provisions for bypassing all this. They use
non-standard features, and are thus off topic here. For discussion
of them go to a newsgroup that discusses your particular system.

--
Some informative links:
news:news.announce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html

May 11 '06 #4
Alan wrote:

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).

I changed the program by adding a second getchar()

.....
char x;
.....
x = getchar();
getchar();
....

Program now works the way I wanted it to. Seems like the second getchar()
"absorbs" the '\n' from pressing ENTER.

Thanks for all your replies.

Alan

May 13 '06 #5
Alan <i.****@octopus.com.au> writes:
Alan wrote:
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).


I changed the program by adding a second getchar()

....
char x;
....
x = getchar();
getchar();
...

Program now works the way I wanted it to. Seems like the second getchar()
"absorbs" the '\n' from pressing ENTER.


That's a good start, but what happens if the user types two characters
before pressing ENTER? Or presses ENTER immediately, without typing
anything else first?

What you really want to do (I suspect) is:

Read a single character from stdin.
If it's a '\n' you're done.
If not, skip everything up to and including the next '\n'.

Another way to express this is:

Read a line from stdin and return its first character.

except that you don't need to store the entire line.

Wrapping this in a function would be a good exercise. And don't
forget to deal with EOF.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
May 13 '06 #6
Groovy hepcat Alan was jivin' on Thu, 11 May 2006 14:07:08 +1000 in
comp.lang.c.
getchar() problem's a cool scene! Dig it!
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)
But of course.
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).


You can't portably do that. However, your implementation or third
party libraries may provide extentions or add-ons that do what you
want.
<OT>
Since you are in a Unix environment, look up getch() in the curses
(or ncurses or lcurses or...) library.
</OT>

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?
May 14 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2230
by: Cam | last post by:
Hi everyone, Before I answer to a (hopefully) helpful reply to this post, I have been rapped over the knuckles for 'top-posting' and I do not wish to be a learner poster who observes poor...
21
639
by: clusardi2k | last post by:
/* The below code on SGI will wait for you to enter 2 things, but on Linux it will only wait the first time. I can make the code work by replacing the scanf with: char data ; fgets...
1
3692
by: White Spirit | last post by:
I'm trying to use getchar() to read alphanumeric data as follows:- char input; /* Take a string of input and remove all spaces therein */ int j = 0; while ((input = getchar()) != '\n') { if...
13
12373
by: broeisi | last post by:
Hello, Can someone help me out with this one? The following program should read characters till it met the EOF (-1) on my pc. I'm running linux and using the gcc compiler version 3.4.5. But...
11
2473
by: shekhardeodhar | last post by:
The program compiles properly (most of it is from k&r) but the second function (here character_count) gives wrong answer. Can someone please explain why ? #include<stdio.h> #define IN 1...
26
4490
by: tesh.uk | last post by:
Hi Gurus, I have written the following code with the help of Ivor Horton's Beginning C : // Structures, Arrays of Structures. #include "stdafx.h" #include "stdio.h" #define MY_ARRAY 15
20
636
by: Senthil-Raja | last post by:
The getchar() function is expected to fetch the next character in the input stream and return it. But, when I wrote a program using this function, it looks like the reading of the input stream...
9
5127
by: primeSo | last post by:
// FIRST int main(void){ int c, i = 0; char cArray; while( (c = getchar()) != '\n' && c != EOF){ cArray = c; i ++; }
2
3090
by: kalar | last post by:
I want to read a line and put each word of this line in a linked list but i must use getchar.My problem is on how to read a line with getchar.(forget linked lists) i make this #include <stdio.h>...
22
3520
by: arnuld | last post by:
Mostly when I want to take input from stdin I use getchar() but I get this from man page itself: "If the integer value returned by getchar() is stored into a variable of type char and then...
0
7204
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7091
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7282
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7464
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
5018
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4680
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3171
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3162
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
391
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.