Ali
Ali

Reputation: 10453

How to get two number from a string and convert to int in one variable?

I'm trying to finish up my homework and this is the last thing I couldn't figure it out since this afternoon.

Say for example I have string in the array like this ABCD24EFG and I want to get that number 24 in a variable that I initialize which type is int

I can do it with one single number and convert it like this

number_holder = array_name[4] - '0';

and I will get 2 in the number_holder but how can I get the whole like 24 and convert them into int type?

Upvotes: 0

Views: 182

Answers (3)

ScarCode
ScarCode

Reputation: 3094

You can use this logic.

number_holder=array_name[4] - '0';
number_holder=number_holder*10 + (array_name[5] - '0');

This way you can also handle array values like ABCD243EFG, ABCD2433EFG ...

ASCII value for integers 0-9 are 48 - 57 ..So use this for finding integers in array.

   number_holder=0;
   For (int i=0;i<arraylength;i++) 
    {
        if(array[i]<58 && array[i]>47)
        number_holder=number_holder*10+array[i] - '0';
    }    

You will have your result in number_holder.

Upvotes: 1

vikiiii
vikiiii

Reputation: 9456

Try

    number_holder_1 = array_name[4] - '0';
    number_holder_2 = array_name[5] - '0';

You will get both number. And perform

number = number_holder_1  * 10 + number_holder_2 ;

If the number must not be 2 digits , then you can use a for loop to get the required number.

Upvotes: 1

D&#233;j&#224; vu
D&#233;j&#224; vu

Reputation: 28830

You can use the famous algorithm

n = 0
while (char = nextchar()) {
  n = n*10 + digit(char)
}

in pseudo language

Upvotes: 3

Related Questions