STEPHEN bui STEPHEN bui - 6 days ago 5
C Question

Code can't get an n-digit numbers from a string in C

I wanna ask how it can not get integer from a string

for example, here are my code:

int main() {
char str[] = "ababbababa-1998";
int nr = atoi(str);
printf("%d\n", nr);
return (EXIT_SUCCESS);
}


when running, it print out 0 but not 1998, how can I fix it ?

Answer

In your case you can use strtok.

int main() {
    char str[] = "ababbababa-1998";
    char * const first_part = strtok(str, "-");
    if (first_part == NULL) {
        return 1;
    }
    char * const second_part = strtok(NULL, "-");
    if (second_part == NULL) {
        return 1;
    }
    int nr = atoi(second_part);
    printf("%d\n", nr);
    return 0;
}

You can look at Why is there no strtoi in stdlib.h? for error check atoi.