hdsalbki <hd******@gmail .comwrites:
I have below a small program to echo back what character the user
types. It's working OK but prints a extra prompt between every
character. what can I do? I'm new in C and my book is very
difficult...
thanks for any help.
#include<stdio. h>
main()
{
char a;
while(1)
{
printf("\nPleas e type a character: ");
scanf("%c",&a);
printf("\nYou typed: %c",a);
}
}
The program is actually doing just what you told it to do. In
response to the prompt, you typed, say, an 'x'. You didn't see
anything happen, so you pressed the return key (or enter, or however
it's labeled). You typed two characters, 'x' and return, and your
program reported each one.
The issue here is input buffering. (This is distinct from output
buffering, which I discussed in a separate followup.) Though your
scanf call asks for only one character, it doesn't complete until
you've entered a line of text. The new-line character is part of that
line.
More precisely, the scanf call *waits* for a full line of input, but
it only *consumes* a single character. Any other characters in the
line are left waiting in a buffer to be consumed by the next call to
scanf.
Try changing the second printf to:
printf("\nYou typed: '%c'",a);
so the output character is surrounded by single quotes. This will
show you more clearly that it's actually reading and printing each
character you type, including new-line.
Try typing just the return key, with nothing preceding it.
Try typing several characters, such as xyz<return>.
What you'd probably *like* to do is read a single character without
waiting for a complete line. C provides no guaranteed way to do that.
See question 19.1 of the comp.lang.c FAQ, <http://www.c-faq.com/>.
Or you can read a single character and then discard the remainder of
the input line. See the rest of this thread for various ways to do
that.
Text input in C is line-oriented. Usually the best way to handle it
is to use fgets() to read a full line at a time into a string, then
use other functions to process the string. You'll get to that later.
(Using fgets() introduces some issues for very long lines; that can
also wait for later.)
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"