【发布时间】:2017-04-10 10:07:12
【问题描述】:
所以我必须为一项作业制作一个银行程序,而我的教授想要每个“操作”的日志文件(他对此真的很模糊,我决定记录输入和输出)。我遇到的问题是,每次我调用一个新函数时,我都必须重新打开文件,它会覆盖以前存在的内容。据我所知,重复使用 .open 会导致我所在的任何函数忽略之前的输出。
我尝试声明一个全局 ofstream 希望它会改变,但问题仍然存在。冲洗和/或关闭似乎没有帮助,但我完全有可能滥用它们或语法错误。下面的代码是main函数、read_accts函数、menu函数。如果我在调用 read_accts 函数之前终止程序,日志文件将显示“有多少帐户?”但是如果我允许程序调用其他两个函数,那么日志文件只有菜单文件的输出。我为这篇长篇文章道歉,但我不知道出了什么问题。
int main()
{
ofstream log;
log.open("Log.txt");
int MAX_NUM = 100;
BankAccount account[MAX_NUM];
int num_accts = 0;
char selection = 'Z';
cout << "How many accounts are there?" << endl;
log << "How many accounts are there?" << endl;
cin >> MAX_NUM;
read_accts(account, MAX_NUM, num_accts);
cout << endl;
cout << "There are " << num_accts << " accounts" << endl;
log << "There are " << num_accts << " accounts" << endl;
cout << endl;
print_accts(account, MAX_NUM);
cout << endl;
`
while (selection != 'Q' && selection != 'q')
{
menu();
cin >> selection;
log << selection;
switch (selection)
{
case 'W':
case 'w':
withdrawal(account, num_accts);
break;
case 'D':
case 'd':
deposit(account, num_accts);
break;
case 'N':
case 'n':
new_acct(account, num_accts);
break;
case 'B':
case 'b':
balance(account, num_accts);
break;
case 'I':
case 'i':
account_info(account, num_accts);
break;
case 'C':
case 'c':
close_acct(account, num_accts);
break;
case 'Q':
case 'q':
print_accts(account, num_accts);
break;
default:
cout << "Invalid selection" << endl;
log << "Invalid selection" << endl;
}
cout << endl;
}
print_accts(account, MAX_NUM);
cout << "Goodbye" << endl;
log.close();
return 0;
}
int read_accts(BankAccount account[], int MAX_NUM, int &num_accts)
{
ofstream log;
log.open("log.txt", std::ofstream::app);
string f;
string l;
int social;
int acct;
string type;
double bal;
int i = 0;
ifstream readfile;
readfile.open("bankdatain.txt");
if (!readfile)
{
cout << "Can't open input file." << endl;
log << "Can't open input file." << endl;
exit(1);
}
while (readfile >> f >> l >> social >> acct >> type >> bal)
{
account[i].setfname(f);
account[i].setlname(l);
account[i].setssnum(social);
account[i].setacctnum(acct);
account[i].settype(type);
account[i].setbalance(bal);
i++;
num_accts++;
}
return num_accts;
}
void menu()
{
ofstream log;
log.open("Log.txt");
cout << "W - Withdrawal" << endl;
log << "W - Withdrawal" << endl;
cout << "D - Deposit" << endl;
log << "D - Deposit" << endl;
cout << "N - New account" << endl;
log << "N - New account" << endl;
cout << "B - Balance" << endl;
log << "B - Balance" << endl;
cout << "I - Account Info" << endl;
log << "I - Account Info" << endl;
cout << "C - Close Account" << endl;
log << "C - Close Account" << endl;
cout << "Q - Quit" << endl;
log << "Q - Quit" << endl;
cout << "Please make your selection: " << endl;
log << "Please make your selection: " << endl;
}
【问题讨论】:
-
您可以在附加模式下打开文件。 cplusplus.com/reference/fstream/fstream/open