Convert String to Integer

Code

#include <stdio.h>
#include <stdint.h>

/*
only parse the first part: +/- num, return if other symbol in beginning
convert num str to integer
*/

int custom_atoi(const char *str) {
    // early return if str doesn't start with valid num
    if ((*str != '+') && (*str != '-')  &&
        (*str < '0' && *str > '9')) {return 0;}
    
    bool negative = false;
    if (*str == '-') { 
        negative = true;
        str++;
    }
    else if (*str == '+'){
        str++;
    }


    int num = 0;
    while (*str != '\0'){
        if (*str < '0' || *str > '9') {break;}

        num = (num * 10) + (*str - '0');
        str++;
    }

    if (negative){return num * -1;}
    else {return num;}
}

int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);

    // Remove newline
    uint8_t i = 0;
    while (str[i]) {
        if (str[i] == '\n') {
            str[i] = '\0';
            break;
        }
        i++;
    }

    printf("%d", custom_atoi(str));
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

123abc

Expected Output

123