On Fri, 3 Mar 2006 10:19:19 +0800, "Argento" <>
wrote in comp.lang.c:
> I was curious at the start about how ungetc() returns the character to the
> stream, so i did the following coding. Things work as expected except if I
> change the scanf("%c",&j) to scanf("%d",&j). I don't understand how could
> scanf() affect the content of i[0] and i[1]. Can someone tell me why?
Your program has so many instances of undefined behavior that there is
nothing at all that the C standard has to say about what it should do.
> #include <stdio.h>
> #include <ctype.h>
>
> void main()
The C standard requires that main() be defined with a return type of
int in a hosted environment, unless you have a C99 conforming compiler
that specifically documents that it accepts "void main()", and I will
most certainly bet that you do not. This means your program is
undefined.
> {
> char i[2], j;
> printf("Please input a two digit number:");
> i[0]= getchar();
> i[1]= getchar();
> ungetc(i[1],stdin);
> ungetc(i[0],stdin);
You haven't checked the return value of the ungetc() function,
particularly the second one. Only one character of push back is
guaranteed by the standard. The second one could have failed.
> scanf("%c", &j); //scanf("%d",&j);
'j' is a character and has a size of one byte (with 8 or more bits).
If you pass scanf() a "%d" conversion specifier and the address of
'j', you are telling scanf() to write an int into that one byte. On
your platform int has more than one byte, and so won't fit into 'j'
which only has room for a single character. You are lying to scanf()
when you use "%d" and this causes undefined behavior.
> fflush(stdin);
The fflush() function is not defined for input streams, more undefined
behavior.
> printf("\nYou entered %d in decimal and %c in character mode for
> i[0]",i[0],i[0]);
> printf("\nYou entered %d in decimal and %c in character mode for
> i[1]",i[1],i[1]);
> printf("\nYou entered %d in decimal and %c in character mode for j",j,j);
>
> getchar();
>
> }
Fix the undefined behavior in your program and then ask questions if
you are puzzled about what it does.
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://c-faq.com/
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html