Sean
Sean

Reputation: 867

How to read in a string of Numbers into an array

I am working on a programming assignment in which we are making our own BigNum class. One of the constructors needs to be set up so that it can take a number from a string (i.e. 342567) and reads it into an array. However if the number were 0000000342567 it would have to be able to skip over the 0s and just read 342567.

Where is what i have so far but am lost on trimming the 0s

BigNum::BigNum(const char strin[])
{
    size_t size = strlen(strin);
    positive = true;
    capacity = size;
    digits = new size_t[capacity];
    used=0;

    while(used<size)
    {
        if(strin[size - used -1] =='-')
        {
            positive = false;
            size --;
        }
        else if(strin[size - used -1] =='+')
        {
            size --;
        }
        else
        {
            digits[used] = strin[size - used -1] - '0';
            used++;
        }
    }
}

Here is the assignment description if it helps http://csel.cs.colorado.edu/%7Eekwhite/CSCI2270Fall2011/hw2/Homework2.pdf

Upvotes: 0

Views: 394

Answers (3)

Ayush
Ayush

Reputation: 42450

Add this just before your while loop:

for (int i=0; i < size; i++)
{
    if (strin[i] >= '1' && strin[i] <= '9')
    {
        used = i;
        break;
    }
}

This way, your while loop begins reading the string only from the index where the number actually begins, skipping over all leading 0s.

This should handle the leading sign as well:

BigNum::BigNum(const char strin[])
{
    size_t size = strlen(strin);
    positive = true;        
    used=0;

    if (strin[0] == '+' || strin[0] == '-')
    {
        //set positive or negative
        used++;
    }
    while (used < size)
    {
        if (strin[used] != '0')     
            break;

        used++; //used will only increment if above if condition failed.
    }

    int digitIndex = 0;
    digits = new size_t[size-used]; //create digits array here so it isn't larger than needed

    while(used<size)
    {        
         digits[digitIndex++] = strin[used++];      
    }
}

Upvotes: 1

Tamer Shlash
Tamer Shlash

Reputation: 9523

You just need to add another while loop before the one you have.

But just some other hints:

You can't change the sign of the number at any digit, the sign depends only on the very first charachter. So if you had a string like -2345, that'll be ok, but if you had something other like: 234-88 then this should be invalid, what will you do with this then?

Also the digits array shouldn't really be equal to size, but rather should drop the sign digit if it did exist, so how will you deal with capacity?

Hope that's helpful!

Upvotes: 0

Mysticial
Mysticial

Reputation: 471229

Here's a hint:

Write a separate loop at the beginning that skips over all the zeros.

Upvotes: 3

Related Questions