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.
To convert an array of strings to an array of numbers, call the map() method on the array, and on each iteration, convert the string to a number. The map method will return a new array containing only numbers. Copied! const arrOfStr = ['1', '2', '3']; const arrOfNum = arrOfStr.
We can convert char to int by negating '0' (zero) character. char datatype is represented as ascii values in c programming. Ascii values are integer values if we negate the '0' character then we get the ascii of that integer digit.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With