> Convert array of digits into an integer in C++?

Convert array of digits into an integer in C++?

Posted at: 2014-12-18 
The "best" way is nearly always debatable. But "a way" based upon Luc's conceptual approach would be:

unsigned int cvt( char v[], size_t n ) {

? ? unsigned int num= 0;

? ? for ( size_t i= 0; i < n; ++i )

? ? ? ? num *= 10U, num += v[i] - '0';

? ? return num;

}

The use of (unsigned int) for a return value is used because you probably don't need to allow for the use of a negative sign. (And the code above doesn't handle one, either.) The use of size_t for the 2nd parameter is simply to match up with the use of sizeof() operator results, but could be (int) or (unsigned int) if you prefer it.

Something like this:

int num = 0;

char[] v = {'1', '2','5'};

for(int i=0;i<3;v++){

num*=10;

num+=v[i]-'0';

}

//value stored in num