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.
So, the idea is to convert character numbers (in single quotes, e.g. '8') to integer expression. For instance char c = '8'; int i = c - '0' //would yield integer 8; And sum up all the converted numbers by the principle that 908=9*100+0*10+8, which is done in a loop.
It isn't that hard to deal with the character array itself without converting the array to a string. Especially in the case where the length of the character array is know or can be easily found. With the character array, the length must be determined in the same scope as the array definition, e.g.:
For strings you, of course, have
strlen
available.With the length known, regardless of whether it is a character array or a string, you can convert the character values to a number with a short function similar to the following:
Above is simply the standard char to int conversion approach with a few additional conditionals included. To handle stray characters, in addition to the
digits
and'-'
, the only trick is making smart choices about when to start collecting digits and when to stop.If you start collecting
digits
for conversion when you encounter the firstdigit
, then the conversion ends when you encounter the first'-'
ornon-digit
. This makes the conversion much more convenient when interested in indexes such as (e.g.file_0127.txt
).A short example of its use:
Note: when faced with
'-'
delimited file indexes (or the like), it is up to you to negate the result. (e.g.file-0123.txt
compared tofile_0123.txt
where the first would return-123
while the second123
).Example Output
Note: there are always corner cases, etc. that can cause problems. This isn't intended to be 100% bulletproof in all character sets, etc., but instead work an overwhelming majority of the time and provide additional conversion flexibility without the initial parsing or conversion to string required by
atoi
orstrtol
, etc.I personally don't like
atoi
function. I would suggestsscanf
: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
andstrtol
. Also, there is a nice more-detailed insight intosscanf
(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 theatoi
function is deprecated and should not be used in newer code.Why not just use atoi? For example:
Gives me, as expected:
Update: why not - the character array is not null terminated. Doh!