0

I have this code to break up numbers entered at the console and return them and I do the same for negative numbers, but here is the strange behaviour I enter 0123and the number gets converted to 83. I am new to objective-c and c, so I need some explanation why this happened. I also noticed from debuting this code that the change actually takes place in the scarf functionnot even in the main code block. Here is my code:

//
//  main.m
//  ex-5.9
//
//  Created by george on 05/07/2016.
//  Copyright © 2016 george. All rights reserved.
//  Program to reverse the digits of a number

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        int number, right_digit;


        NSLog(@"Enter your number.");
        scanf("%i", &number);

        if(number < 0){           
            number = ABS(number);
            do {
                right_digit = number % 10;
                NSLog(@"%i", right_digit);
                number /= 10;
            } while (number != 0);

            NSLog(@"-");

        }else{
             do {
                 right_digit = number % 10;
                 NSLog(@"%i", right_digit);
                 number /= 10;
             } while (number != 0);
        }


    }
    return 0;
}
gavinb
  • 19,278
  • 3
  • 45
  • 60
George Udosen
  • 906
  • 1
  • 13
  • 28

1 Answers1

4

It's behaving as documented - a leading zero prefix to an integer constant denotes an octal number, so 0123 (in base 8) is just 83 (in base 10).

Look up the documentation of scanf for the full details of these conversions. Hexadecimal is also supported. If you're writing Objective-C code, I suggest you look at the NSString parsing routines which have a better interface for this sort of thing.

gavinb
  • 19,278
  • 3
  • 45
  • 60
  • 1
    You typed faster. :) All I'd add is that the following link is a good SO on using scanf and NSString: http://stackoverflow.com/questions/3220823/using-scanf-with-nsstrings – Nate Birkholz Jul 05 '16 at 13:37
  • 2
    To be clear, this will only happens with the `%i` format specifier. With `%d` the leading zeros are ignored and the decimal number is converted. – Weather Vane Jul 05 '16 at 14:10