Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert char array to a int number in C

Tags:

arrays

c

char

int

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.

like image 583
SpcCode Avatar asked Apr 18 '12 07:04

SpcCode


People also ask

How do you convert an array to a number?

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.

Can we convert a character to integer in C?

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.


1 Answers

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.

like image 81
penelope Avatar answered Sep 28 '22 13:09

penelope