使用函数操作文件

时间:2014-01-17 15:57:26

标签: c++ function

您好我正在尝试编写程序,该程序允许用户从帐户转移金额(该帐户是文本文件“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 positive\n";
        }
        else if (balance < amount)
        {
            std::cout << "Insufficient funds\n";
        }
        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();
}

1 个答案:

答案 0 :(得分:2)

当编译器在使用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);