c++ - 从文件中读取值、更改值和更新文件

标签 c++ file-io

我正在处理一个简单的工资申请。我有一个包含 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/

相关文章:

c++ - 如何在 C++ 程序中捕获负整数输入?

c++ - 使用批处理重新启动 C++ 控制台应用程序不会关闭网络连接

file-io - 编写 netcdf4 文件比编写 netcdf3_classic 文件慢 6 倍,而文件大 8 倍?

file-io - 发生错误时 io.lines(filename) 是否关闭文件?

c++ - 是否应该尽可能使用前向声明而不是包含?

c++ - 使用 std::reference_wrapper 作为 std::map 中的键

java - 从多个视频部分创建单个视频文件

c++ - 如何找到我的进程在 Linux 中打开的文件句柄?

c - 当我读取这个文件时,如何读取所有记录

python - 读取格式独立于换行符的非常大的文件