How to write and then read from file

Hi All

I have data like this that should be stored in a file

W 200
I 300
D 200
D 300

How do i store them in a file and be able to read them latet to do calculations with them. What is the simplest way to do this?
Eg. The W stands for Withdrawal, I for Interest and D for Deposit. So, i have a bank balance which i need to change based on which line the program read from the text file. So the program will read the first line and see a W and will then subtract 200 from the balance, etc

As i'm a newbie to C++ what is the easiest way to achieve this?
You need to understand streams:

Use an iftream to read from a file.
    ifstream trans;
    char trantype;
    double amt;"transactions.txt");
    //  Check that open succeeded
    //  Loop until eof
    trans >> trantype >> amt;
    //  process
    // end of loop

Thanks for the help and the link. For me to understand what i must do is more important than to get code. So, I know about streams yes. How do i get the info in the file? How does trans >> trantype >> amt do that? How does the program know trantype is the W, D, I's, etc?

I can write an amount like this to file - myoutfile << "3750.40 \n"; but how does the program know 3750.40 is a variable for amt? Do i need to declare all the amounts before using them?
How do i get the info in the file?

Use a text editor to create the file?

Well, you could write a program to output the values to the file. But where would the program get its data, would it be from the user typing values perhaps? Or maybe from another file...?

As for the data in the file, by itself it has no meaning. It only becomes meaningful when you write a program to interpret the data according to your requirements. In other words, you use your understanding of the data to determine how the program needs to be written.

Last edited on
Thanks Chervil

Ok, lets say the file is suppose to be created manually. Lets not make it complicated. So I have the file with the data. How do i get the program to read the data and store it so that it can be displayed?

So the line says W 250.00
Is the line trans >> transtype >> amt enough to store W in transtype and 250.00 in amt?
trans is an input stream. It behaves in very much the same way as the standard input cin.

Just as you can do cin >> number; etc. to get keyboard input, you can get input from a file in a similar way.

Maybe you need to review the concepts, and also rather than trying to write a complete program, just play around with short examples to get a feel for how things work.
Topic archived. No new replies allowed.