Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Help me understand this execution!? (http://www.go4expert.com/forums/help-understand-execution-t20771/)

rforravi 26Jan2010 20:35

Help me understand this execution!?
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 27Jan2010 08:35

Re: Help me understand this execution!?
See the Values of a, b and c before adding as that will help you understand why things behave the way they are.

rforravi 27Jan2010 20:04

Re: Help me understand this execution!?
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' ? :p :nonod:

Gene Poole 27Jan2010 21:52

Re: Help me understand this execution!?
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 28Jan2010 03:57

Re: Help me understand this execution!?
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.

All times are GMT +5.5. The time now is 17:47.