extract numbers from a character string


I am trying to extract numbers from a character string like the one below one by one .The only thing i could find out was that you can convert character string into a int by using atoi function present in stdlib but it converts the whole string into a single large int.


1
2
3
4
5
6
7
8
9
10
11
12

const char str[] ="73167176531330624919225119674426574742";
const char str2[] = "7"
const char* ch = str;

int x =  atoi(str2)

std::cout<<*ch; //outputs   7
std::cout<<(int)*ch //outputs the ascii value of 7 that is 55 so i cant use it in integer operations

std::cout<<atoi(ch)// outputs some absurdly large number ....
std::cout<<x; // prints 7 



Is there some built in fnction like atoi(ch) which outputs the first integer 7?
Last edited on
The numbers are stored numerically in ascii, so you can do the conversion manually by subtracting the literal value of '0' from each individual character. That will convert the ascii code of '0' to the integer value of 0:

1
2
3
4
5
6
7
const char str[] = "7316176";

int x = str[0] - '0';
cout << x;  // <- prints 7

x = str[1] - '0';
cout << x;  // <- prints 3 
thanks !
Topic archived. No new replies allowed.