Convert char to int

c121hains used Ask the Experts™
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
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

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

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

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.

Actually, you can can check with isdigit()
Announcing the Winners!

The results are in for the 15th Annual Expert Awards! Congratulations to the winners, and thank you to everyone who participated in the nominations. We are so grateful for the valuable contributions experts make on a daily basis. Click to read more about this year’s recipients!

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);
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!
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


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.


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

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial