Question:

I need some help with a c programming function. The function is suppose to read in a octal number by string,

by  |  earlier

0 LIKES UnLike

and then convert the string to an integer using atoi. If possible please include a simple example. Thanks.

 Tags:

   Report

1 ANSWERS


  1. atoi() doesn't support octal numbers, at least not in standard C. strtol() does support it:

    #include <stdlib.h>

    ...

    long int number = strtol(theString, NULL, 8);

    ...

    will return the long int value of an octal number in theString.

    If you're reading the string from the console, you can make scanf() interpret the input as octal for you:

    #include <stdio.h>

    ...

    unsigned int num;

    ...

    scanf("%o", &num);

    ...

    The only use of the atoi function I could think of is if you'd process each digit individually:

    #include <stdlib.h>

    int readOct(char *theString) {

    int num = 0;

    int i=0;

    char digit[2]=" ";



    // each digit

    while(theString[i] != '\0') {

    // higher octal place value for previous digits

    num *= 8;

    // add current digit

    digit[0] = theString[i];

    num += atoi(digit);

    i++;

    }



    return num;

    }

    But then it would be easier to make use of the fact, that C represents characters as numbers:

    int readOct2(char *theString) {

    int num = 0;

    int i=0;



    // each digit

    while(theString[i] != '\0') {

    num *= 8;

    num += theString[i] - '0';

    i++;

    }



    return num;

    }

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.