Mail Archives: djgpp/1997/10/22/23:01:31
On 20 Oct 1997 14:18:41 GMT in comp.os.msdos.djgpp Marsel (martsobm AT uv DOT es)
wrote:
: #include <stdio.h>
: main()
: {
: char c;
: int n;
: printf("Write an integer: ");
: scanf("%d",&n);
: printf("Write a character: ");
: scanf("%c",&c);
: printf ("The integer is: %d and the character is: %d \n",n,c);
: }
You forgot to put in a `return' statement ;). That's not the reason for
the problem, though...
: Why the secong scanf function does not wait until the caracter is introduced
: ?. the c variable always contain the caracter \010
Are you sure? Unless I'm very much mistaken, that's the backspace
character. If anything, I'd expect to see '\n'. The reason this problem
occurs is that the first scanf call requires you to enter a line, and then
reads an integer from the start of it, leaving the rest of the line in the
buffer. The second call then picks up the first character of this
remainder, which ought to be some whitespace character, e.g. '\n' if the
user just pressed Enter after entering the number.
: I know it will be better to use c=getch(); but why the this code does not
: work well ?
I personally don't like scanf much for most purposes. If you use fgets,
instead, to do the first read (and atoi the result) you'll pull the LF
characeter out of the buffer too, and leave nothing in it after the call.
Then a call to getchar() will work. Since stdin is line-buffered, though,
the getchar() call will require a whole line of text to be typed, and
return just the first character, leaving the rest in the buffer, so you'll
be back to square one...
The stdio functions are fairly limited, and you may have to use conio for
your purposes.
--
Regards,
george DOT foot AT merton DOT oxford DOT ac DOT uk
- Raw text -