W
W
Wolf56782020-08-07 18:03:38
C++ / C#
Wolf5678, 2020-08-07 18:03:38

How to convert an array of numbers from char to int?

How to convert an array of char to int numbers in a class that works with "long" numbers?

class Long
{
private:
  char arr[100];
public:
  Long();
  void input();
  void show();
  Long operator+(const Long& l1);
};


void Long::show()
{
  for (int i = 0; i < 5; i++)
  {
    cout << (arr1[i]);
  }
}

Long Long::operator+(const Long& l1)
{
  Long l2;
  int k = 0;
  for (int i = 4; i >= 0; i--)
  {
    if (i == 4)
    {
      if ((arr[i] + l1.arr[i]) >= 10)
      {
        l2.arr[i] = (arr[i] + l1.arr[i]) % 10;
        k = 1;
      }
      else if ((arr[i] + l1.arr[i]) < 10)
      {
        l2.arr[i] = (arr[i] + l1.arr[i]);
      }
    }
    if (i != 4)
    {
      if (k == 1)
      {
        l2.arr[i] = (arr[i] + l1.arr[i] + k) % 10;
        if ((arr[i] + l1.arr[i] + k) >= 10)
        {
          k = 1;
        }
        else if ((arr[i] + l1.arr[i] + k) < 10)
        {
          k = 0;
          continue;
        }
      }
      if ((arr[i + 1] + l1.arr[i + 1] + k) < 10)
      {
        if (k == 0)
        {
          l2.arr[i] = (arr[i] + l1.arr[i]) % 10;
          if ((arr[i] + l1.arr[i] + k) >= 10)
          {
            k = 1;
          }
          else if ((arr[i] + l1.arr[i] + k) < 10)
          {
            k = 0;
            continue;
          }
        }
        else if (k == 1)
        {
          l2.arr[i] = (arr[i] + l1.arr[i] + k);
          if ((arr[i] + l1.arr[i] + k) >= 10)
          {
            k = 1;
          }
          else if ((arr[i] + l1.arr[i] + k) < 10)
          {
            k = 0;
            continue;
          }
        }
      }
    }
  }
  return l2;
}

I understand that the code is written very clumsily, but I would like the sum of two numbers to be displayed in the show method. And in general will it work with char?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tsarevfs, 2020-08-07
@tsarevfs

Show seems to work fine for numbers that are 5 digits long. You don't need to cast to int for this.

Long a, b;
a.input();
b.input();
Long sum = a + b;
sum.show();

Your code can be greatly simplified:
* Formula l2.arr[i] = (arr[i] + l1.arr[i] + k) % 10; works for the first digit too (i == 4 for you), since at the beginning k = 0.
* The value of k can also be calculated without if: k = (arr[i] + l1.arr[i] + k) / 10 ;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question