Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using atoi with char

Tags:

c

atoi

Is there a way of converting a char into a string in C?

I'm trying to do so like this:

   char *array;

   array[0] = '1';

   int x = atoi(array);

   printf("%d",x);
like image 650
John Doe Avatar asked May 26 '10 18:05

John Doe


5 Answers

char c = '1';
int x = c - '0';
printf("%d",x);
like image 178
BlueRaja - Danny Pflughoeft Avatar answered Oct 16 '22 18:10

BlueRaja - Danny Pflughoeft


If you're trying to convert a numerical char to an int, just use character arithmetic to subtract the ASCII code:

int x = myChar - '0';
printf("%d\n", x);
like image 40
Platinum Azure Avatar answered Oct 16 '22 20:10

Platinum Azure


You need to allocate memory to the string, and then null terminate.

char *array;

array = malloc(2);
array[0] = '1';
array[1] = '\0';

int x = atoi(array);

printf("%d",x);

Or, easier:

char array[10];

array = "1";

int x = atoi(array);

printf("%d",x);
like image 5
Paul Michaels Avatar answered Oct 16 '22 20:10

Paul Michaels


How about:

   char arr[] = "X";
   int x;
   arr[0] = '9';
   x = atoi(arr);
   printf("%d",x);
like image 4
Jacob Avatar answered Oct 16 '22 19:10

Jacob


You can convert a character to a string via the following:

char string[2];
string[0] = '1';
string[1] = 0;

Strings end with a NUL character, which has the value 0.

like image 2
Steve Emmerson Avatar answered Oct 16 '22 19:10

Steve Emmerson