How to convert a char array into an int in C++?

How to convert an array of chars to an int in C?

  • I need to take an array of characters and convert it to an int. Ex: --------------------------------------… char a []; a[0] = '1'; a[1] = '2'; a[2] = '3'; --------------------------------------… Is there anyway to take this array and make an integer that has value 123?

  • Answer:

    in addition to your code above... have an int array to hold the data... int intArray [ 3 ]; assign the char value to the int array casting it as a type int. intArray[0] = int (a [0]); or... you can use a function called atoi ( )...that take a character and returns an int. intArray = atoi (a[0] );

fbi14105 at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

int j=(a[0]-'0')*100 + (a[1]-'0')*10 + (a[2]-'0'); '1' - '0' = 1 '2' - '0' = 2 '3' - '0' = 3 So this becomes 1*100 + 2*10 + 3, or 123, as desired. Update: For an array of any length, just make it a loop. You can use this: int num_entries; int i,j; char array[]; /* code to stuff array and num_entries */ j=0; for(int i=0; i<num_entries; i++) j=(j*10)+(array[i]-'0'); /* j now holds your answer */ Do you see why the 'j=(j*10)+..' works? If the array is terminated by a zero byte, you can use this: char *ptr=&array[0]; while(*ptr!=0) { j=(j*10)+(*ptr-'0'); ptr++; } CAUTION: Functions like 'atoi' can *only* be used on an array terminated by a zero byte.

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.