0

My scenario is as follows:(C++)

In char a[10], the array a[] has elements (numbers) like '1','2','3' etc....

Say a[0] = '1';
a[1] = '2';
a[2] = '3';

Now a[] is storing 3 characters '1', '2' and '3'. I want to store this into an int as 123 (An integer 123).

How to achieve this in C++ ?

codeLover
  • 3,720
  • 10
  • 65
  • 121
  • There is literally tons of stuff on string to int conversions all over SO and the internet. – chris Jun 29 '12 at 09:46

4 Answers4

4

a[3] = 0 is a must. If your string isn't null-terminated, most methods won't work.

After that, it's a simple number = atoi(a)

SilverbackNet
  • 2,076
  • 17
  • 29
3

Depending on what the value after a[2] is...

int total = 0;

for ( int i = 0; i < a[i]; i++ ) {
    total *= 10;
    total += a[i] - '0';
}
SpacedMonkey
  • 2,725
  • 1
  • 16
  • 17
1
#include <iostream>

int array2int(char a[]) {
  int i = 0;
  int value = 0;
  while (a[i]) {
    value *= 10; 
    value += a[i] - '0';
    i++;
  }
  return value;
};

int main(void) {
  char a[10] = "123";
  int value = array2int(a);
  std::cout << value << std::endl;
};
Gareth A. Lloyd
  • 1,774
  • 1
  • 16
  • 26
1
#include <iostream>
int ca2int(char *array, size_t len){
    int v = 0;
    while(len--)
        v = 10*v + *array++ - '0';
    return v;
}

int main(){
    char a[10];
    a[0] = '1';
    a[1] = '2';
    a[2] = '3';

    std::cout << ca2int(a, 3);
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70