Thread: Using fstream

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    36

    Using fstream

    I am having a little trouble using fstream. Currently i am working on a project which simulates a bank. The thing is, i have a file that lists the current balances of the accounts. For example, here is a file:
    ************
    25000
    15000
    5000
    2000
    ************

    This shows that the user whose index number is one has a balance of $25000. My program simulates interest and transactions. However, at the end of the program, that balance changes. My problem is that i do not know how to change the first line of the program so that it reads a different number.

    Say, i am the 3rd user to sign up for an account, i would have an index number of 3 and i have $5000. I widthdraw and deposit money so that i now have a current balance of say $9875. How do i edit the file so that the $5000 is overwritten by '9875'?

    Here is the code for such a program

    Code:
    /*
      Name: The Bank
      Copyright: 2005
      Author: Sridar Ravi
      Date: 28/05/05 16:27
      Description: A Bank
    */
    
    #include<iostream>
    #include<conio.h>
    #include<utility.h>
    #include<math.h>
    #include<fstream>
    
    
    using namespace std;
    
    //------------------------Prototypes and Constants------------------------------
    
    const double Interest=0.03;
    const double Natural_E=2.712;
    
    ofstream NameFile("Name.txt", ios::app);
    ofstream PINFile("PIN.txt", ios::app );
    ofstream TransFile("Trans.txt", ios::app);
    ofstream CurrentBalFile("CurrentBal.txt",ios::);
    ofstream DateFile("Date.txt", ios::app);
    ofstream StartFile("Start.txt", ios::app);
    
    //-----------------------User-defined Account Class-----------------------------
    class Account
    {
          private:  
                  double Balance;
                  double Original;
                  double DepositMoney;
                  double WidthdrawMoney;
                  
                  int Years;              
                  int Code;
                  
                  string Name;
                  string NewName;
                  
                  double NewPIN, StartingMoney;
                  
                                        
                  double InterestPay(int Years)
                  {
                         double temp,temp2;
                         
                         temp=Interest*Years;
                         temp2=pow(Natural_E,temp);
                         
                         
                         return Balance*temp2;
                  }
                  
                  
                  
          public: 
                 Account();
                 ~Account();
                 
                 char AskAns;
                 char Ask();
                 
                 char choice;
                 void Choice(char &choice);
                 
                 char Deposit_Ask;
                 char DepositAns();
                 
                 char Widthdraw_Ask;
                 char WidthdrawAns();
                 
                 void CurrentBalance();
                 void Deposit();
                 void Widthdraw();
                 void GetBalance();
                 void ListTransaction();
                 void Instructions();
                 void NumYears(int &Years);
                 void Login();
                 void InterestAdd();
                 void Create();
                 void Delete();
                 
                 int index;
                 
                 
    };
    
    //-----------------Constructor and Methods and Destructor-----------------------
    
    Account::Account() //Constructor
    {       
    			/*Sets everthing equal to 0*/
    
                      Balance=0;
                      DepositMoney=0;
                      WidthdrawMoney=0;
                      Years==0;
                      index=0;
    }
    
    Account::~Account(){}
    
    void Account::GetBalance()
    {
         cout<<"Your balance as of now is $"<<Balance<<endl;
    }
    
    void Account::Instructions() 
    {							
    	cout<<"Welcome to The Bank of Sridar Ravi!\n\n";
    	cout<<"This bank only allows for savings accounts at this time!\n\n";
    	cout<<"Checking accounts and money market accounts will become available soon\n\n";
    	cout<<"This bank allows you to enter in your initial balance\n";
    	cout<<"and then you will wait for the money to grow\n\n";
    	cout<<"You can also make transactions if you wish\n\n\n\n";
    	cout<<"To proceed, please press ENTER now\n";
    	getch();
    	
    	system("cls");
    }
    void Account::CurrentBalance() 
    {
         double ref2;
         int q;
         ifstream CurrentBalFile("CurrentBal.txt");		      
         for(q=1;q<=10000;q++) //Finds Balance based on index number
         {
                             CurrentBalFile>>ref2;
                             if(q==index)
                             {
                                         break;
                                         }
         }
         Balance=ref2;
         Original=Balance;
         cout<<"Your current balance is $"<<Balance<<endl;
         cout<<"Press ENTER to proceed\n";
         getch();
         system("cls");
    }
    
    void Account::Deposit() 
    {
         					
         cout<<"How much do you want to deposit into your account?: $";
         DepositMoney=GetDouble(0);
         Balance+=DepositMoney;
         cout<<"The new balance with the interest added now is: $"<<Balance<<endl;
         
    }
    
    void Account::Widthdraw()						
    {
         cout<<"How much would you like to widthdraw?: $";
         WidthdrawMoney=GetDouble(0,Balance);
         Balance-=WidthdrawMoney;
         cout<<"Please wait while we process you new balance...\n";
         Wait(1500);
    }
    
    
    void Account::ListTransaction()  
    {								
    	cout<<"\n\n";
    	cout<<"Your Transaction\n\n";
    	cout<<"Your original balance was: $"<<Original<<"\n";
    	cout<<"You deposited: $"<<DepositMoney<<endl;
    	cout<<"You widthdrew: $"<<WidthdrawMoney<<endl;
    	cout<<"The new balance is: $"<<Balance<<endl;
    	
    	for(int w=1; w<=index; w++)
    	{
                if(w==index)
                {
                            CurrentBalFile<<Balance;
                            }
        }
    	
    	
    	cout<<"This bank gives you an interst rate of "<<Interest*100<<"% compounded continuously\n";
    	cout<<"We hope you are content with the transaction!\n";
    	}
    
    char Account::Ask()  
    {					
    	cout<<"What would you like to do now? \n";
    	cout<<"A---------Another Transaction\n";
    	cout<<"N---------New User\n";
    	cout<<"Q---------Quit\n";
    	cout<<"Please enter one of the choices: ";
        cin>>AskAns;
        
    	return AskAns;	
    }
    
    void Account::NumYears(int &Years)
    {
         cout<<"How many years has passed since the last transaction or starting this account?: ";
         cin>>Years;     
    }
    
    void Account::Login()
    {
         cout<<"Please enter in your User ID: ";
         cin>>Name;
         
         repeat_code:
                          
         cout<<"Enter your access number: ";
         cin>>Code;
         
         
         string temp="a";
         int ref;
         
         ifstream NameFile("Name.txt");
         ifstream PINFile("PIN.txt");
         
         for(index=1;temp!=Name;index++)  //searches for the Name to get index number
         {
                                        NameFile>>temp;
                                        if(temp==Name)
                                        {
                                                      break;
                                                      }
         }
         
         for(int i =1; i<=10000;i++) // finds the PIN corresponding to index
         {
                                        PINFile>>ref;
                                        if(index==i)
                                        {
                                                    break;
                                                    }
                
         }
         
         if(Code==ref) //checks to see if PIN is good
         {
                      cout<<"Thank You!\n";
                      }
         else
         {
             cout<<"Invalid PIN!! Enter again....\n";
             goto repeat_code;
             }
             
         cout<<"You are now logged in. Pess any key to continue...\n";
         getch();
    }     
    
    
    void Account::InterestAdd()
    {
         NumYears(Years);
         Balance=InterestPay(Years); //pays interest
         cout<<"The new balance with the interest added now is: $"<<Balance<<endl;
    }
    
    char Account::WidthdrawAns()
    {
         cout<<"Would you like to widthdraw?: ";
         cin>>Widthdraw_Ask;
         return Widthdraw_Ask;
    }
     
    char Account::DepositAns()
    {
         cout<<"Would you like to deposit?: ";
         cin>>Deposit_Ask;
         return Deposit_Ask;
    }
    void Account::Create()
    {
         system("cls");
         cout<<"Enter the User ID of the account that you wish to make: ";
         cin>>NewName;
         NameFile<<NewName<<endl;
         
         cout<<"Now, please enter the PIN number that you want to create: ";
         cin>>NewPIN;
         PINFile<<NewPIN<<endl;
         
         cout<<"How much money would you like to put into this account?: ";
         cin>>StartingMoney;
         StartFile<<StartingMoney<<endl;
         CurrentBalFile<<StartingMoney<<endl;
         
         cout<<"Congratulations! Your account is now created\n";
         cout<<"Please press ENTER to end this program, so that you can access your account\n";
         getch();
    }
     
    void Account::Choice(char &choice)
    {
         cout<<"What would you like to do?\n";
         cout<<"A-------Create new account\n";
         cout<<"B-------Log In\n";
         cout<<"C-------Delete Account\n";
         
         cout<<"Your Choice: ";
         cin>>choice;    
    }
    
    void Account::Delete()
    {
         cout<<"You are about to delete this account....\n";
         
         cout<<"Your account has been deleted.\n";
         cout<<"Press Enter to end this program now\n";
         getch();
    }
    
    //-------------------------------------Main--------------------------------
    int main()
    {
    	
    	cout.setf(ios::fixed); cout.precision(2); //Rounds everything to 2 decimal places
    	
     newuser:
    	
        Account X; 	
    	X.Instructions();
    	char choice;
    	X.Choice(choice);
    	
        if(choice=='a')
    	{
                 X.Create();
                 return 0;
                 }
        else if(choice=='b')
        {
             X.Login();
             }
        else if(choice=='c')
        {
             X.Delete();
             return 0;
             }
        
        X.CurrentBalance();
        
        start:
        
        int years;
        char Answer;
        
        X.InterestAdd();    
        
        if(X.DepositAns()=='y')
        {
                                    X.Deposit();
                                    }
        if(X.WidthdrawAns()=='y')
        {
                                    X.Widthdraw();
                                    }
        
        
        X.ListTransaction();
                                      
        Answer=X.Ask();
       
        if(Answer=='Q')
        {
        	cout<<"Have a nice day!\n";
        	    	        
        	getch();
        	system("cls");
        }
        
        if(Answer=='A')
        {
        	cout<<"Okay! Press Enter now\n";
        	getch();
        	system("cls");
        	goto start;
        }
        
        if(Answer=='N')
        {
             cout<<"Logging Out...";
             Wait(2000);
             system("cls");
             goto newuser;
             }    
        return 0;
    }
    I also have another question. when instantiating an object of fstream, i can use:
    Code:
     
    fstream MyFile("myfile.txt", ios::in | ios::out | ios::app)
    but i didn't use that cause i want to read and write to the file and append to it when i am writing to the file. The following code above does not do that. Thus, i have to put:

    Code:
    ofstream MyFile("myfile.txt", ios::app)
    this outside of main, and the
    Code:
    ifstream MyFile("myfile.txt")
    inside main or in the functions. I can combine them, bu te results are not what i want.

    Help me out here....

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    I would read in the data using an ifstream and store all the information within the program (and then let the ifstream close). Only when the user exited or requested a save would I re-write all the data out to the file using an ofstream. That way the file is only read in once and is usually only written out once, and you don't have to worry about seeking to the correct position in the file to change something.

  3. #3
    Registered User
    Join Date
    Sep 2004
    Posts
    36
    And how would i do that?

  4. #4
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    If you know how to declare dynamic memory then I'd use it to declare an array of 10000 Accounts and read the account values into the array one at a time. Alternatively, since you are using the STL string class you could use the STL vector class, which expands to fit so to speak, so you don't have to fiddle with dynamic memory on your own. Either way, remember that indexes for an array/vector is zero based, so the index will be one less than the account number.

    If you want to use a single fstream to both read and write to a file, then you can declare it, associate it with whatever file you want, and open it in whatever mode you want. Then when you want to read instead of write, or visa versa, you need to close the stream and reopen it in whatever mode you want next.
    You're only born perfect.

  5. #5
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    An example of using a vector and reading/writing to a file:
    Code:
    #include <algorithm>  // For the copy function
    #include <fstream>
    #include <vector>
    #include <iostream>
    #include <iterator>   // May or may not need this for istream_iterator/ostream_iterator
    
    using namespace std;
    
    int main()
    {
        vector<double> balance;            // This will hold all of our balances from the file
        ifstream input("CurrentBal.txt");
    
        // Read in all values from CurrentBal.Txt into our vector.
        copy( istream_iterator<double>(input), istream_iterator<double>(), back_inserter(balance) );
        input.close();                     // Don't need this open anymore
    
        // Write all values read from file to the console (one value per line)
        copy( balance.begin(), balance.end(), ostream_iterator<double>(cout,"\n") );
    
        // Modify one of the values, make sure balance[2] exists first, this is
        // just for a quick test.  balance[2] is the 3rd value in the vector.
        balance[2] = 9875.0;  
    
        // Write all values back to the file (one value per line)
        ofstream output("CurrentBal.Txt");
        copy( balance.begin(), balance.end(), ostream_iterator<double>(output,"\n") );
    
        return 0;
    }
    If you don't want to work with istream_iterators and ostream_iterators and the copy function, then you can replace those with more conventional looping code.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    I think you need to rethink your design a little bit. You have an Account class. What you should do is have a separate instance of that class for each account in the bank. You could also have a Bank class. That bank class would hold all the accounts, probably in a vector. The functions that read data from the files and write data to the files would be part of the bank class, and the account specific data would be part of the Account class.

    Once you make that change, then it would be easier to understand how reading the data from the file all at once would work.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with fstream, one variabile for write and read
    By Smjert in forum C++ Programming
    Replies: 3
    Last Post: 02-03-2009, 10:19 PM
  2. Fstream. I/O
    By kevinawad in forum C++ Programming
    Replies: 2
    Last Post: 07-07-2008, 09:19 AM
  3. ARGH! fstream errors
    By OttoDestruct in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2004, 10:37 PM
  4. Are fstream and ofstream incompatible?
    By johnnyd in forum C++ Programming
    Replies: 5
    Last Post: 03-19-2003, 12:21 PM
  5. Problems with fstreams.
    By mosdef in forum C++ Programming
    Replies: 7
    Last Post: 06-19-2002, 03:36 PM