reading value from a file, altering value and updating file

Hi I am working on a simple wages application. I have a menu with 4 options and a text file called "shop-account" that simply contains the value 100. For option one the user is suppose to be able to transfer an amount from this 100. The user should be able to make multiple transactions but cannot overdraw the account.

Currently I have have just been opening the file and declaring the value 100 to the int "balance", then asking the user to input the amount to be transferred ("NewAmount") and simply subtracting it. However this only works for one transaction.

When I go back and try and make a second transfer it again subtracts from 100, not the updated amount. So I was wondering if anyone know how I would go about getting the file to update after each transaction?

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  int balance;
int NewAmount;


fstream infile;
infile.open("shop-account.txt");
infile >> balance;

do {


cout << "1. Transfer an amount" <<endl;
cout << "2. List recent transactions"<<endl;
cout << "3. Display account details and current balance"<<endl;
cout << "4. Quit" << endl;

cout << "Please enter menu number"<<endl;

cin >> selection;


switch(selection)
{
case 1: 
cout << "You have choosen to transfer an amount" << endl;
cout << "How much do you wish to transfer from the shop account?"<<endl;
cin >> NewAmount;
cout << balance - NewAmount << endl;

break;


case 2:
cout << "Here are you're recent transactions" <<endl;
cout << "" << endl;
cout << "" << endl;
break;

case 3:
cout << "The account names is:" << name << endl;
cout << "The account number is:" << number << endl;
cout << "The current balance is\n\n" << endl; //Need to get cuurent balance still
break;

case 4:
return 0;
break;

default:
cout << "Ooops, invalid selection!" << endl;
break;
}

}while(selection != 4);

system("pause");
return 0;
}
Put curly braces around lines 5-7 so the file doesn't stay open the whole program. After you change the value you need to open the file with a std::ofstream using the std::ios::trunc flag (making he file empty) and then just write the new balance to the file.
Topic archived. No new replies allowed.