Hi all,
I'm taking a C++ programming course and I'm having a problem completing another one of the assignments...
Requirements: Create a file called accounts.dat that has account numbers (int) and balances (double) and program to display the following information from accounts.dat created above:
a. All accounts with balances less than zero
b. All accounts with balances greater than zero
Here's what I've written but it doesn't neatly group the accounts with balances less than zero and balances greater than zero.
Should I go about creating two files (accounts_pos.dat) and (accounts_neg.dat) to display the data? Or is there a way to neatly organize the data read from file and display as required above?
As always, thank you for the help.
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
|
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int acct_num = 0;
double balances;
//open the file for reading
fstream inp;
inp.open("accounts.dat");
//check to see if file is readable
if(!inp.good())
{
cout << "Unable to read file\n";
return 0;
}
while(!inp.eof())
{
inp >> acct_num >> balances;
if (balances<=0)
{
cout << "Account Number\tBalance" << endl;
cout << acct_num <<"\t" << balances << endl;
}
else
{
cout << "Account Number\tBalance" << endl;
cout << acct_num <<"\t" << balances << endl;
}
}
inp.close(); //close file handle
return 0;
}
|
When I run this, I get the account number and balance for all the accounts but in no particular order.
Here is what is displayed:
Account Number Balance
11112 1000
Account Number Balance
11113 5000
Account Number Balance
11114 6000
Account Number Balance
11115 -500
Account Number Balance
11116 -900
Account Number Balance
11117 700
Account Number Balance
11118 10
Account Number Balance
11119 -5
Account Number Balance
11120 0
|