使用函数操作文件

manipulating file using functions

本文关键字:文件 操作 函数      更新时间:2023-10-16

嗨,我正在尝试编写一个允许用户从帐户转移金额的程序(帐户是文本文件"shop",仅包含值 100)。

我希望拥有它,以便用户可以进行任意数量的转账,而不会透支帐户。该文件还需要在每次事务后更新。谁能帮助我解决我出错的地方?

int read_balance(void);
void write_balance(int balance);
#include <limits>
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int _tmain(int argc, _TCHAR * argv[])
{
    std::cout << "You have choosen to transfer an amount" << std::endl;
    std::cout << "How much do you wish to transfer from the shop account?" << std::endl;
    int amount = 0;
    if (std::cin >> amount)
    {
        std::cout << "DEBUG: amount:" << amount << "n";
        int balance = read_balance();
        if (amount <= 0)
        {
            std::cout << "Amount must be positiven";
        }
        else if (balance < amount)
        {
            std::cout << "Insufficient fundsn";
        }
        else
        {
            int new_balance = balance - amount;
            write_balance(new_balance);
            std::cout << "New account balance: " << new_balance << std::endl;
        }
    }
    system("pause");
    return 0;
}
int read_balance(void)
{
    std::ifstream f;
    f.exceptions(std::ios::failbit | std::ios::badbit);
    f.open("shop.txt");
    int balance;
    f >> balance;
    f.close();
    return balance;
}
void write_balance(int balance)
{
    std::ofstream f;
    f.exceptions(std::ios::failbit | std::ios::badbit);
    f.open("shop.txt");
    f << balance;
    f.close();
}

正如编译器在使用 stdafx.h 的预编译标头时警告的那样,#include "stdafx.h"必须是代码的第一行。所以最好从

#include "stdafx.h"
#include <limits>
#include <iostream>
#include <fstream>
using namespace std;
int read_balance(void);
void write_balance(int balance);