-2

I have a char array like the following

charArray[0] = '1'
charArray[1] = '2'
charArray[2] = '3'
charArray[3] = '4'
charArray[4] = '5'

How to combined the char value of above array into a int like the following ? But I don't want to combined all the value in to a int

I only want to combined charArray[0]~charArray[3] into int

int number = 1234;

How to combined the char value of above array into a string ?

Martin
  • 2,813
  • 11
  • 43
  • 66
  • On what grounds are you disregarding the last digit? No 5's allowed? No more than 4 digits? No result larger than 10,000 allowed? – Jongware May 24 '14 at 15:28

3 Answers3

4

I hope, by showing you the following line, this will give you a better idea how to tackle programming problems.

int number = (charArray[0] - '0')*1000 + 
             (charArray[1] - '0')*100 + 
             (charArray[2] - '0')*10 + 
             (charArray[3] - '0');

Cheers.

Steger
  • 887
  • 7
  • 16
2

You should use the atoi function:

int atoi (const char * str);

recives a string and returns it as a value of type int.

and the function stncpy:

char * strncpy ( char * destination, const char * source, size_t num );

Copies the first num characters of source to destination.

Create a new string(with the strncpy function) containing only the 4 first chars of the charArray and then use the function atoi on the result

This way you could take any size of string you want from the charArray, without manually having to calculate the number

Example (based on your code, assuming you want to keep the charArray as is without changing it) :

int main(void)
{
   char charArray[6]="12345";
   char newcharArray[5];//one char less than charArray
   strncpy(newcharArray,charArray,4);
   printf("%d\n",atoi(newcharArray));
}
YonBruchim
  • 101
  • 6
0

you can also use alternative methods.

Please check: Converting string to integer C

You can also use strtoumax() function.

see the example : http://pic.dhe.ibm.com/infocenter/zos/v1r12/index.jsp?topic=%2Fcom.ibm.zos.r12.bpxbd00%2Fstrtoumax.htm

Community
  • 1
  • 1
Murat
  • 72
  • 10