user3834500
user3834500

Reputation: 13

Using fstream to import a text file to a variable?

I'm trying to create a simple program that acts like an ATM for learning purposes. I have a working program so far, but now I want to "take it to the next level" if you will and import my banks balance from a text/csv file and then assign to a variable, if any changes are made to the balance I also want to write those changes to said text file. I've searched the web so far and haven't been able to find much information that seems particularly relevant to my question.

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

//calculates money withdrawal.
int main(){
    double currentBalance = -250.63;
    double prevBalance = currentBalance;
    double withdrawal = 0;
    double deposit = 0;
    double deficit = currentBalance;
    double updatedWithdrawal = 0; //(currentBalance - withdrawal)
    double updatedDeposit = 0; //(currentBalance + deposit)
    string answer = "blah";

    cout << "Welcome to bank bro's banking services.\nWhat would you like to do? Withdrawal, Deposit, or View Account Status(VAS): ";
    cin >> answer; // asks the user if they intend to withdrawal, or deposit.

    if (answer == "VAS"){
        if (currentBalance > 0)
            cout << "\n Your account is in good standing." << endl;
        else{
            cout << "\n You currently owe: $" << deficit << endl;
        }
        cout << "\n Your current balance is: $" << currentBalance << endl;
    }
    else if (answer == "vas"){
        cout << "\n Your current balance is: " << currentBalance << endl;
        if (currentBalance > 0)
            cout << "\nYour account is in good standing." << endl;
        else{
            cout << "You currently owe: $" << deficit << endl;
        }
        cout << "\nYour urrent balance is: $" << currentBalance << endl;
    }
    else if (answer == "Withdrawal"){
        cout << "\nHow much would you like to take out? ";
        cin >> withdrawal;
        if (withdrawal > currentBalance)
            cout << "\nYou don't have sufficient funds." << endl;
        else{
            updatedWithdrawal = (currentBalance - withdrawal);
            cout << "You have $" << updatedWithdrawal << " left, cash is dispensed below." << endl;
            cout << "\n\n\n Thank you, come again!" << endl;
        }
    }
    else if (answer == "withdrawal"){
        cout << "\nHow much would you like to take out? ";
        cin >> withdrawal;
        if (withdrawal > currentBalance)
            cout << "\nYou don't have sufficient funds." << endl;
        else{
            updatedWithdrawal = (currentBalance - withdrawal);
            cout << "\nYou have $" << updatedWithdrawal << " left, cash is dispensed below." << endl;
            cout << "\n\n\n Thank you, come again!" << endl;
        }
    }
    else if (answer == "Deposit"){
        cout << "\nHow much would you like to deposit? ";
        cin >> deposit;
        updatedDeposit = (currentBalance + deposit);
        cout << "\nYour previous balance of $" << prevBalance << " \nhas been updated and $" << deposit << 
            " \nhas been added to your account, bringing the total available balance to $" << updatedDeposit << endl;
        cout << "\n\nThank you come again!" << endl;
   }
    else if (answer == "deposit"){
        cout << "\nHow much would you like to deposit? ";
        cin >> deposit;
        updatedDeposit = (currentBalance + deposit);
        cout << "\nYour previous balance of $" << prevBalance << " \nhas been updated and $" << deposit <<
            " \nhas been added to your account, bringing the total available balance to $" << updatedDeposit << endl;
        cout << "\n\nThank you come again!" << endl;
    }
    else{
        cout << "I don't recognize that command, restart and try again." << endl;
    }
    return 0;
}

Any help is greatly appreciated! :)

Upvotes: 0

Views: 1883

Answers (3)

James Kanze
James Kanze

Reputation: 153899

You can use an std::ifstream to read, and an std::ofstream to write. You're already familiar with these to some degree: std::ifstream derives from std::istream, just as the type of std::cin, does, and std::ofstream derives from std::ostream, just as the type of std::cout does; all of the functions which read and write are in the base class (or depend on the base class).

The one particularity of the file streams is that you can open them:

std::ifstream in( filename );
if ( ! in.is_open() ) {
    //  The open failed...
}

Same thing for the output stream.

It's not particularly easy to modify data in an existing file, and the file needs to respect a lot of formatting rules to make it even possible. For this reason, the most frequent way of modifying files is to read them into memory, do the modifications there, and then write the complete file back out. Usually, you'll write the output to a temporary file, check that the stream status is still good after the close, and then use the functions remove and rename to remove the orginal file and rename the new file. This way, if there is a problem writing the file, you don't loose any data.

Upvotes: 1

BenS
BenS

Reputation: 91

This is my first answer to a question, but I just wanted to point out you know you can do else if (answer == "Withdrawal" || answer == "widthdrawal") the || is the or statement, it basically means that at least one of the conditions has to be true in order for the code in the brackets to execute. One thing about programming is make your code is DRY (Don't repeat yourself).

for the file: http://www.cplusplus.com/doc/tutorial/files/ So, anyways onto the file. you're going to want to read about it a bit, but the general process is

string line;
// File will contain a number.
ifstream myfile("balance.txt");
// if the file is open
if (myfile.is_open())
{
    // get the first line of the file and store it to line (string)
    getline(myfile, line);
    // there is a better (foolproof) way to do this, but this will work for no.
    currentBalance = atof(line.c_str());
    // close file when done. always. 
    myfile.close();
}

Upvotes: 1

Alessandro Suglia
Alessandro Suglia

Reputation: 1927

In order to use file in C++ you need an fstream. You should have a look to the documentation http://en.cppreference.com/w/cpp/io/basic_fstream/basic_fstream where is correctly described how to interact with file in C++.

You need an fstream opened in write mode in order to save all the data in the format that you've chosen. After that, you need to open an fstream in read mode in order to read from it the data again.

The file format is up to you. You can serialize data in whetever format you want. You need to remember that, after the serialization process, all the data must be read exactly how they are written.

Upvotes: 1

Related Questions