w3resource

C Language: Custom atoi() function

C - Implementing a custom atoi() function.

The atoi() function is used to convert a character string to an integer value.

Code:

# include <stdio.h>

int my_atoi(const char *str) {
    int result = 0;
    int sign = 1;
    int i = 0;

    // Check for leading sign character
    if (str[0] == '-') {
        sign = -1;
        i++;
    }
    else if (str[0] == '+') {
        i++;
    }

    // Convert digits to integer value
    while (str[i] != '\0') {
        if (str[i] < '0' || str[i] > '9') {
            break;
        }
        result = result * 10 + (str[i] - '0');
        i++;
    }

    return sign * result;
}

int main() {
    const char *str1 = "-1234";
    int result = my_atoi(str1);
    printf("Converted integer: %d\n", result);
    const char *str2 = "1234";
    result = my_atoi(str2);
    printf("\nConverted integer: %d\n", result);
    return 0;
}

Output:

Converted integer: -1234

Converted integer: 1234

The my_atoi() function takes a string as input and returns the corresponding integer value. It checks for a leading sign character and converts the remaining digits to an integer value.

Contribute your code and comments through Disqus.



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

C Programming - How do you pass a function as a parameter in C?

Declaration

A prototype for a function which takes a function parameter looks like the following:

void func ( void (*f)(int) );

This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:

void print ( int x ) {
  printf("%d\n", x);
}

Function Call

When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:

func(print);

would call func, passing the print function to it.

Function Body

As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:

for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
  print(ctr);
}

Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:

void func ( void (*f)(int) ) {
  for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
    (*f)(ctr);
  }
}

Ref : https://bit.ly/3skw9Um