Search code examples
carrayscharint

Convert char array to a int number in C


I want to convert a char array[] like:

char myarray[4] = {'-','1','2','3'}; //where the - means it is negative

So it should be the integer: -1234 using standard libaries in C. I could not find any elegant way to do that.

I can append the '\0' for sure.


Solution

  • I personally don't like atoi function. I would suggest sscanf:

    char myarray[5] = {'-', '1', '2', '3', '\0'};
    int i;
    sscanf(myarray, "%d", &i);
    

    It's very standard, it's in the stdio.h library :)

    And in my opinion, it allows you much more freedom than atoi, arbitrary formatting of your number-string, and probably also allows for non-number characters at the end.

    EDIT I just found this wonderful question here on the site that explains and compares 3 different ways to do it - atoi, sscanf and strtol. Also, there is a nice more-detailed insight into sscanf (actually, the whole family of *scanf functions).

    EDIT2 Looks like it's not just me personally disliking the atoi function. Here's a link to an answer explaining that the atoi function is deprecated and should not be used in newer code.