473,803 Members | 3,534 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 5280
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_setting s, new_settings;
static int peek_character = -1;

void init_keyboard()
{
tcgetattr(0,&in itial_settings) ;
new_settings = initial_setting s;
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_setting s);
}

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

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

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

int readch()
{
char ch;

if(peek_charact er != -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(v oid);
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.annou nce.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_Keit h) 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 "technicall y correct" English; but since when was rock & roll "technicall y correct"?
May 14 '06 #7

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

Similar topics

3
2245
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 netiquette as I am a firm believer in consideration .... to this end, could somebody please tell me how I reply to a message without top-posting? Do I need to have my original post selected when I hit the 'reply' button? Here's my question (and...
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 (data,5,stdin); the_number = atoi (data);
1
3723
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 (!isspace(input)) j++;
13
12422
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 it doesn't. Am I doing something wrong here?.
11
2505
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 #define OUT 0 int word_count();
26
4545
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 happens only after I press the ENTER key. Please someone explain why this is happening. Regards, Senthil-Raja.
9
5151
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
3105
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> #define len 64 int main(void){ char str; int i;
22
3610
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 compared against the integer constant EOF, the comparison may never succeed, because sign-extension of a variable of type char on widening to integer is implementation-defined" while( EOF != (ch = getchar()) ) ....
0
9703
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9565
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10550
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10295
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10069
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9125
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6844
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5501
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5633
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.