tags:

views:

108

answers:

2

hello,

wondering all about C, can you demystify this

I am using turbo C

I have this code

scanf(“%d , %d”,&a,&b);
printf(“%d,%d”,a,b);
scanf(”%c”,&c);
printf(“%d,%d”,a,b);

then scanf for doesnt scan value of c

output is : 1,2

if I use this

scanf(“%d , %d”,&a,&b);
printf(“%d,%d”,a,b);
scanf(”%c ”,&c);//note a blank after %c
printf(“%d,%d”,a,b);

then it scan value of c.

output is 1,2 1,2

same code

scanf(“%d , %d”,&a,&b);
printf(“%d,%d”,a,b);
scanf(”%1s”,&c);
printf(“%d,%d”,a,b);

in this segment value of a will be displayed but value of b will be set 0

output is 1,2 1,0

can you explain the answers of both the questions.

didnt got the answers yet help me.......

+3  A: 

In your last case, it's to do with where values are set up in memory.

The second scanf puts a string of length 1 at the address of c - that is, one character, followed by the null terminator.

Guess where the null terminator goes?

Anon.
It flies out of your nose of course!
D.Shawley
+1  A: 

How do you know that no character is being scanned for c in the first case? I assume it is because you provide a unexhibited print statement and don't see anything.

Read the man page careful about the behavior of the %c specifier:

c
Matches a sequence of width count characters (default 1); the next pointer must be a pointer to char, and there must be enough room for all the characters (no terminating NUL is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.

[emphasis added]

If you input has a form like 1, 2 a the first scan eats the 1 , 2 and leaves the a, at which point the second scan eats the space. Not sure how the second example would work in this case.

Anon. is on the money about the third case.

dmckee