Search code examples
c++arraysfile-iomultidimensional-arrayfstream

C++ text to multidimensional arrays


So I need to make a program that sums numbers from this text file:

3

22 5126717910121751622546

29 88888888888888888888888888888

40 2525255125133485451578436833138834387837

The first line shows the number of rows, and the following lines are the numbers that I need to sum. The first number in one of following lines shows number of digits of the second number.

Output file should be like this:

2525255125222374345594043632149474899271

I figured out that I have to use multidimensional arrays. I'm new to C++ and not used to multidimensional arrays so I need some help. Thanks in advance! P.S. sorry if my English was bad.


Solution

  • Since those integers are quite big, you need to store them in string and define operator + for those strings (actually big integers)

    You can do the following to store them in 1D vector since the "number of digits" is not relevant if you really do BigInteger add. Meanwhile, you only output the sum not the number of digits in result.

       vector<string> data;
       ifstream dataFile("dataInput.txt");   //or you can use stringstream
       long numbers = 0; 
       dataFile >> numbers;
       long digits = 0;
       string currentNum;   
       while (dataFile >> digits >> currentNum)
       {
         data.push_back(currentNum);
       }
       //now add those integers
    

    Add for BigInteger is straightforward.