Help me understand this execution!?

rforravi's Avatar, Join Date: Aug 2008
Go4Expert Member
I've seen a code getting executed
I dint understand as how is that!

Can someone help me understand this ??
(I'm a newbie in C )

The foll. is the code
void main()
int a,b,c;
scanf("%1d %2d %3d",&a,&b,&c);

[THE USER INPUT IS :123456 44 544]

The result is 480 .. !! :-O .. how ??
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
See the Values of a, b and c before adding as that will help you understand why things behave the way they are.
rforravi's Avatar, Join Date: Aug 2008
Go4Expert Member
i've understood that its been adding 1+23+456 .. The value given only in 'a'
But my question is why is it not taking b and c into consideration??
Like. when does it take b and c also ??

Then wht is the use of giving b and c ?
I can declare anyyyyyy number of variables (b,c,d,e,.......) but it adds up only 'a' ?
Gene Poole's Avatar, Join Date: Nov 2009
You are specifying a width parameter in the %d specifier ("%[width]d" scans a maximum of "width" characters). scanf stops scanning once that many characters are read so the next %d scans from the last position.
xpi0t0s's Avatar, Join Date: Aug 2004
Yes, that's the whole point of the exercise, to introduce you to the concept of "formatted input". If you specify a format for the input, and the user enters something in a different format, then the result will not be what the user expected. Ideally the user interface should specify that a should be 1 digit, and throw an error when the user enters 123456 instead of just accepting it and continuing.

When dealing with users maximum flexibility is preferable. They *will* enter stupid input, and it's your program's responsibility to sort out what they've done and respond accordingly. Formatted input is fine if you can guarantee the input format, but you can't when it comes to users, so this is why programmers (who aren't in class any more) *don't* use scanf and *do* use more generic functions like gets.