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 ) Thx The foll. is the code void main() { int a,b,c; scanf("%1d %2d %3d",&a,&b,&c); printf("Sum=%d",a+b+c); } [THE USER INPUT IS :123456 44 544] The result is 480 .. !! :-O .. how ??
See the Values of a, b and c before adding as that will help you understand why things behave the way they are.
kk 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:
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.
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.