Vinicius <cv********@cli ck21.com.br> wrote:
the following code does not work:
What exactly does not work? I think it works as designed, but perhaps
not as expected by you.
Have you tried to print out `option' after each read?
"
...
void main(void)
int main(void); {
char option;
printf("Choose an option: ");
option = toupper(getchar ());
printf("Chosse another option: ");
scanf("%c", &option);
...
"
It shows "Choose an option: Choose another option ". Why?
On my system the two messages are on two different lines,
unless you run them with stdin redirected, like this:
./a.out <In
Whether I put two lines "fflush(std in)" before the inputs, the same
above occurs.
Don't do it, it's undefined. What possibly could it do?
If stdin is your terminal, then getchar() will read the first character
entered, and scanf() will read the next character that is in the *stream*,
which is possibly a carriage-return - depending on how you enter the
characters:
a<CR>b<CR> - first `option' is 'a', second time it is '\n'
ab<CR> - first it is 'a', then it is 'b'
a b<CR> - first read 'a', then ' '
a<CR>b<CR> - first read ' ', then 'a'
etc...
If the scanf line looked like this:
scanf(" %c", &option); /* note the extra space */
then scanf would skip any white-space characters before reading
next character:
a<CR>b<CR> - read 'a' (getchar()), then skip '\n' and read 'b' (scanf())
a<CR> <TAB>b<CR> - after reading 'a', '\n', ' ' and '\t' are ignored
and 'b' gets into `option'
a<CR>b<CR> - getchar() reads first ' ', scanf() skips the second ' '
and reads 'a'
Note, on top of all above, the terminals are line-buffered, so you can't
enter any characters without entering (pressing) <CR>. The situation
is a little different when your stdin is a file.
scanf() is a useful function, but not easy to understand, and if you're
a beginner, leave it for later. Better use fgets() for reading; atoi()
and strtol() families for conversions, but maybe sscanf() would prove
easy to use here as well.
To know scanf() you have to _carefully_ read its description. It is
not an "inverse" of printf(), and the format string similarities with
that of printf() are only apparent.
--
Stan Tobias
sed 's/[A-Z]//g' to email