need to save data

Hey...I want to do a project based on a bank with various functions. One of them is to display the accounts in the bank. I need to save the accounts using structures for this, so that I don't have to input it during the run every time. Could someone help me with the syntax for this? Thanks... :)

Last edited on
You are going to need to use a file to store the data, and to read it back in.
For an introduction to that topic, see the tutorial:
http://www.cplusplus.com/doc/tutorial/files/

Without knowing the details of your structures and how you are using them it isn't possible to give any more specific help.

Well, my structure looks like this:
struct baccount
{ char accno[6], acctype[2], fname[20], lname[20];
long amt;
};

The function will have to display the name, and amount in the accounts when the user chooses the option.
Thanks for that. I suspect it may need a bit of fine-tuning. Some of the fields may need increasing in length, remember a c-string needs an extra byte for the terminating null character. Thus acctype[2] can store a string of length 1 character.

For now, you could save a baccount to file a bit like this:
1
2
3
4
5
6
    const char delim = '\t';
    std::ofstream fout("accounts.txt");

    fout << acct.accno << delim << acct.acctype << delim 
         << acct.fname << delim << acct.lname   << delim 
         << acct.amt << '\n';


That will write all the items on a single line separated by the tab character used as a delimiter.

Reading the data back in, I'd prefer to read the whole line at a time and then split it using a stringstream, but it still amounts to almost the same thing, use getline with the same delimiter,
 
file_in.getline(acct.accno,   delim);

and so on.

There are always additional considerations, what to do if the data is longer than the string in which it is to be stored, how to handle the last field on the line, any trailing whitespace etc.


Another approach is to use a file in binary format and read or write the entire structure in a single operation. I'd leave that idea until you have a bit more experience with files, I don't recommend it as a starting point.
Topic archived. No new replies allowed.