Convert char array to a int number in C

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 – atoisscanf 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.

Leave a Comment

deneme bonusu veren sitelerbahis casinomakrobetceltabetpinbahispolobetpolobet giriÅŸpinbahis giriÅŸmakrobet giriÅŸpulibet giriÅŸmobilbahis giriÅŸkolaybet giriÅŸ