C++ problems with end-of-file
The way you're reading from file seems to be ok, but the way you're populating arrays seems odd.
You read first line of file, both account id and balance to accountID and accountBalance, and then in a loop you're reading accounts ids from file to arrayA with index of accountID and balances to arrayB of index accountBalance so respectively, arrayA[1] and arrayB[0] (the first line of accounts.txt which you read and written to accountID and accountBalance)
So the array is mostly unchanged, you keep ovewriting index 1 of arrayA and index 0 of arrayB.
Instead of that you should not read from the file before the loop, so you won't discard any data, and then make yourself another variable where you will keep last index you have written to, set it to 0 and as you read from file and write to array with index defined by that variable, increase the index variable.
So ditch this line:
inf >> accountID >> accountBalance;
and make yourself this one before the loop:
int index = 0;
and then instead of:
inf >> arrayA[accountID]; inf >> arrayB[accountBalance];
do:
inf >> arrayA[index];
inf >> arrayB[index];
And don't forget to add index++ at the end of the loop.
And if you want to print the values right away then fix the index for printing too.
accountID and accountBalance seems to be unneeded in this function at all.
You can set yourself some constant or pass another argument to your function for the max index of array so you won't go out of bounds.
FYI, file can end between first inf >> and the second one.
Also the last empty line will make your app to another loop iteration, as it is not end of file, but there are no more values, it won't succeed to read those, and will insert gibberish to 16th index of arrays, if your arrays are idnexed from 0 - 14 (15 cells) then it will write to somewhere where it shoudl not, and it will destroy some of the data or crash your application.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now