Array input from file

I cant seem to get the input from the file into the array to work correctly. When I remove the file input portion and initialize the arrays in the code it works properly.

#include <iostream>
#include <fstream>
using namespace std;

int main()
{


int n1[20];
int n2[20];
int ans[21];
int answer;
char tc;

int carry = 0, value = 0;

ifstream infile;
ofstream outfile;

infile.open("numbers.txt");
outfile.open("outfile.txt");



for(int i = 0; i <20; i++)
{
infile.get(tc);
n1[i] = tc - '0';
}

for(int i = 0; i <20; i++)
{
infile.get(tc);
n2[i] = tc - '0';
}

for(int i = 19; i >=0; i--)
{

answer = n1[i] + n2[i] + carry;
if (answer > 9)
{
ans[i]= (answer % 10) + carry;
carry = 1;
}
else
{
ans[i] = answer;
carry = 0;
}
}

for(int i = 0; i < 20; i++)
{
cout << ans[i] << " ";
}

infile.close();
outfile.close();

return 0;
}
Are you getting errors? Or are you just not getting the expected output?
Is it true that all you are trying to do is read two integers from a file, add them together, and write the sum to the output file?
I am not getting errors. I am just getting an unexpected output. I am just adding them together. When i program the arrays in it works correctly, so i figure the way i am geeting it from the file is incorrect.
Why are you reading it that way? That's about the hardest way you could possibly read
two integers from a file (hence my question).

Your code assumes that the file is formatted such that it is exactly 40 bytes in length,
no newlines, and the first integer is right justified in a field width of 20 characters
with leading zeros, and that the second integer is also right justified in a field width
of 20 characters with leading zeros.

Ie,

0000000000000000012800000000000000000256

would yield the right answer (128+256). Any other format to the file would cause your
program to generate erroneous output.
I am sorry I wasnt very clear. My problem states that 2 twenty digit numbers must be added together by use of arrays and I cant figure out how to read the numbers into an array correctly.

doc format

11111111111111111111
11111111111111111111
Last edited on
Ok, in that case you need to read in the newline between the
two numbers.

Something like

1
2
3
char ch = 0;
while( infile && infile >> ch && ch != '\n' )
    /* empty loop body */;


Also, this is wrong:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for(int i = 19; i >=0; i--)
{
    answer = n1[i] + n2[i] + carry;
    if (answer > 9)
    {
        ans[i]= (answer % 10) + carry;
        carry = 1;
    }
    else
    {
        ans[i] = answer;
        carry = 0;
    }
}


It can be way simpler.

Each digit of the answer = ( n1[i] + n2[ i ] + carry ) % 10.
Each time, carry = ( n1[i] + n2[ i ] + carry ) / 10.

No need for an if-else.

Topic archived. No new replies allowed.