# Convert char to int

on
How do you convert a number in char datatype to an int datatype?  Basically I have this string that contains numbers and letters but I need to extract a number at a certain location within the string.  Each time I try to cast the char to an int, I keep getting the ascii index number instead.  For example:
My attempt:
int a;
CString myString = “text9text”;
a = (int)(myString[4]);        //the contents of "a" will not be 9 like I want it to be but will be something like 62 or whatever
Comment
Watch Question

Do more with

EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
If you are absolutely certain that the character indeed represents a number, you can write:

int num = myString[4] - '0'; // zero

Commented:
You have to consider the beginn of numbers of the ascii alphabet in order to hack this.

for example.

a = myString[4]-'0';

But your solution wouldn't be very flexible in this way. A better idea is to extract the value vie the function.

a = atoi( myString+4 );

So you aren't limited to a single digit.

Commented:
Actually, you can can check with isdigit()
Commented:
If you know exactly format of incoming string, then use sscanf function

const char* myString = "text9text";
char str1[5]; // array must be long enough to take correspondent substring
char str2[5]; // the same comment
long digit1;
sscanf(myString, "%s%d%s", str1, &digit1, str2);

Commented:
Your are returning the int value of a, you need to return the char value.

int a;
CString myString = "text9text";
a = myString[4];
cout << (char)a << endl;

Hope that helps!

Commented:
Here is another example, now you can use the value as an integer capable of subtraction, addition…ect.

const char * ptr;
const char * myString = "text9text";

ptr = &myString[4];
cout << atoi( ptr ) + 100 << endl;     // add the value 100 to 9

Commented:
barnwillyb

You'r making things overly complex. myString is already a perfect pointer to the beginning of the cString, thus you don't need to dereference the fourth symbol just to take the adress of it, make

ptr = myString+4;

However, there is no need at all to introduce another variable just to have a pointer since myString IS already a pointer to the beginning of the string you can do:

cout << atoi( mySTring+4 )+ 100 << endl;

as well. Which is less code and nicer to read.

Commented:
Perfect!  This idea will work beautifully!
Thank you all for your help.

Do more with