C++ how to convert a char to int?Like char '4' to int 4 .Help please!

In a given input string i have letters and digit .I need to know all the digits.
Like,hjasd7afaf8faf
from that i have to find out 7;8
I know atoi()
But it wont work here as the digits may be anywhere in string,…
Can anyone suggest any library function…
I can write a function by myself similar to binary search but i’m searching for more effective ways.
And is there any library function too convert from string to int s no matter how they are in sequence or not in string…Like 123k2j3122 to 123;2;3122
Thanks a lot :slight_smile:

I’ve written one.But looks like there’s something wrong with it

int ctoi(char p)
{
    char ch[10]={'0','1','2','3','4','5','6','7','8','9'};

    while(start<=ennd){
    mid=(start+ennd)/2;
    if(p==ch[mid])
        return mid;
   else if(p<ch[mid])
    ennd=mid-1;

    else if(p>ch[mid])
    {
        start=mid+1;
    }

}
}

This would do

if ('0' <= p && p <= '9')
    integer = p - '0';

for converting a digit to its integer. No need of any binary search. You can also remove the if, provided p contains a digit, and the check is unnecessary.

5 Likes

@nabil1997 is this what u want???

1 Like

Yupp,
Actually I totally missed this Thing.
Thanks by the way :slight_smile:

i dont think that ne such fxn exists…also the ques u have asked and the description do not match…pls ask an appropriate ques…also to extract all ints from a string can be easily done by writing a small fxn…as u said!!!

1 Like

no,i asked 2 questions.and what are you saying that ques and description do not match…I dont get that.

and for numbers greater than 9 for eg ‘10’,‘11’ etc

1 Like

10 is 1,0 and 11 is 1,1 …so on

if( s[i]-'0' >=0 && s[i]-'0' <=9)
         result+=s[i]+';' ;

He is asking something different :slight_smile:

u can search through the string for ascii value of integers (48 to 57 )…

int z = char z - 48;
48 is decimal value of 0 char i.e base value .

1 Like