Convert char array to a int number in C

前端 未结 5 1078
梦毁少年i
梦毁少年i 2020-11-30 01:32

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

5条回答
  •  清歌不尽
    2020-11-30 01:51

    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.

提交回复
热议问题