Greetings.
I am having some trouble with a program I made for calculating the first 10 digits of the sum of 100 50-digit numbers (
http://projecteuler.net/problem=13) and for whatever reason, it refuses to read the values from the file i pasted the number in.
This is what I have thus far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#include <iostream>
#include <fstream>
using std::cout;
using std::endl;
int main()
{
const short nLineSize = 100, nColSize = 50, nDigitSize = 10;
char c;
std::ifstream ifs("array.txt");
short anArray[nLineSize][nColSize] = { 0 }, i = 0, j = 0;
for (i = 0; i < nLineSize; ++i)
// the column length is essentially the number of digits in each number, so each row will only contain the digits of one number
for (j = 0; j < nColSize; ++j)
{
ifs >> c;
anArray[i][j] = c - '0'; // convert numeric character to integer
}
ifs.close();
short nDigitSum;
short nDigits[nDigitSize] = { 0 },
p = 0;
for (i = nColSize - 1; i >= 0; --i) // the summing process will be from left to right, just like a basic mathematical sum
{
nDigitSum = 0;
for (j = 0; j < nColSize; ++j)
nDigitSum += anArray[j][i]; // add each line of the same column to the sum
if (nDigitSum > 9) // anything higher than 9 is not a digit anymore
anArray[j - 1][i - 1] += nDigitSum / 10; // so we add its prefix to the next column of digits
nDigits[p] = nDigitSum % 10; // memorize the last digit found in each sum. note that they will be in reverse order
p++;
}
for (i = nDigitSize - 1; i >= 0; --i)
cout << nDigits[i] << ' ';
cout << endl;
return 0;
}
|
What I'm going for is essentially something like this:
123 +
128
----
251
The problem is the above code doesn't work when I paste the 100 50-digit numbers into the file (note that there are no spaces or newlines between the digits). It says the stack around the variable "anArray" was corrupted and I have no idea why.
When I use a more rudimentary set of values, such as 123456123456123456123456123456123456 (123456 pasted 6 times), and set nLineSize, nColSize and nDigitSize to 6, it does what it's supposed to do (it prints 740736, which is 123456 * 6).
So, what am I doing wrong?
Thank you in advance.