使用函数操作文件
manipulating file using functions
嗨,我正在尝试编写一个允许用户从帐户转移金额的程序(帐户是文本文件"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);
相关文章:
- C++二进制文件 I/O 操作速度变慢.数据库如何处理二进制文件?
- 程序未正确执行文件操作
- C++程序在执行文件操作时在Windows与Linux上运行得慢得多?
- 使用文件操作的 XMLFile 解析
- iOS和Android的C 中的文件操作
- 高级 I/O 文件操作,带函数
- 在Linux和Windows C 上处理的低级文件操作
- 如何使用QT Designer?实施最新的文件操作
- c++中的文件操作
- 二进制与文本模式下的文件操作 -- 性能问题
- 在Windows Server 2008上挂接SMB文件操作
- 尝试学习c++中的基本文件操作
- 内核授权文件操作范围在小牛队中已损坏
- 写入文件挂钩未捕获写入文件操作
- 每个目标的生成文件操作
- 文件 I/O 操作 - 奇怪的字符输入
- 是否需要为C/C++中的文件I/O操作创建自己的缓冲区
- C++文件操作
- 使用什么样的API,您可以在OSX中执行read-consistent文件操作,类似于Windows卷影服务
- 更快的文件操作C++