我正在处理一个简单的工资申请。我有一个包含 4 个选项的菜单和一个名为“shop-account”的文本文件,其中仅包含值 100。 对于选项一,用户应该能够从这 100 笔中转账。用户应该能够进行多次交易,但不能 overdraw 账户。
目前我刚刚打开文件并向 int“balance”声明值 100,然后要求用户输入要转移的金额(“NewAmount”)并简单地减去它。然而,这仅适用于一次交易。
当我返回并尝试进行第二次转账时,它再次从 100 中减去,而不是更新后的金额。所以我想知道是否有人知道我将如何在每次交易后更新文件?
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;
}
最佳答案
基本上您的文件只包含一个数据,因此进行部分更新根本没有意义。
您所要做的就是像您一样在开始时阅读它,然后在每次进行交易时将其完全写回。
int read_balance (void)
{
fstream f;
f.open("shop-account.txt");
f >> balance;
f.close();
return balance;
}
void write_balance (int balance)
{
fstream f;
f.open("shop-account.txt");
f << balance;
f.close();
}
然后在您的代码中:
cout << "You have choosen to transfer an amount" << endl;
cout << "How much do you wish to transfer from the shop account?"<<endl;
cin >> NewAmount;
balance -= NewAmount;
write_balance (balance);
cout << balance << endl;
关于c++ - 从文件中读取值、更改值和更新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21123602/