我正在为学校项目编写文件匹配程序。这个想法是,一个程序允许您输入如下信息:1000(账户号码)Jane Doe 54.50(余额)。然后允许您为第二个程序输入帐号和交易金额以合并和更新新的主文件。
这些程序可以很好地协同工作(第二个程序从第一个程序中获取信息,包括任何交易并更新新余额 - 按帐号搜索)但我遇到的问题是名称。
---这里不清楚。当我询问姓名并输入单个字符串时,程序运行正常,如果我尝试输入全名,例如 Jane Doe,我将进入下面提到的循环。
我试过 char name[20] ,这让我陷入无限循环,我必须从程序中“x”出来,我试过将 first 和 lastName 分配给字符串。这适用于写作,但采用输入文件 oldMaster 和事务文件 inTransaction 然后输出新文件 newMaster 的程序无法识别名称。
我也尝试过 getline,但它对我不起作用,可能是程序员错误。
如果可能的话,这应该作为一个数组来完成吗?我想我对我正在编辑文件这一事实感到困惑。答案很好 - 但我喜欢自己想办法,只是想从这里寻找一些指导。
希望这是相当清楚的 - 如果不是,我会很乐意以不同的方式再次解释。只是很沮丧,我离得太近了,却无法解决它。
提前致谢!
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
using namespace std;
void createOldMaster()
{
ofstream oldMaster;
int accountNum;
double balance;
char name[15];
oldMaster.open("oldmast.dat", ios::out);
if(!oldMaster)
{
cout << "Unable to open the file." << endl;
exit(1);
} // end if
cout << "Enter the account number (0 to exit)." << endl;
while(true)
{
cout << "Account Number: ";
cin >> accountNum;
if(accountNum == 0)
break;
else
{
\\ This is where it hangs up if I use a first and last name
cout << "\nName: ";
cin >> name;
cout << "\nBalance : " << endl;
cin >> balance;
oldMaster << accountNum << " " << name << " " << balance << endl;
}
}
} //end createOldMaster
void createTransaction()
{
ofstream inTransaction;
int accountNum;
double balance;
inTransaction.open("trans.dat");
if(!inTransaction)
{
cout << "Unable to open the transaction file." << endl;
exit(1);
}
cout << "Enter the account number and balance (0 to exit): " << endl;
while(true)
{
cout << "Account Number: " << endl;
cin >> accountNum;
if(accountNum == 0)
break;
else
{
cout << "Balance: " << endl;
cin >> balance;
inTransaction << accountNum << " " << balance << endl;
}
}
} //end createTransaction
int main()
{
createOldMaster();
createTransaction();
return 0;
}
最佳答案
最好的办法是尽可能多地使用标准 C++ 库。手边有一份引用资料,如果您愿意的话,甚至可以是 C++ 标准的拷贝,并寻找让您的工作更轻松、代码更短的捷径。
尽可能避免原始数组和原始字符串。尝试使用 std::vector
而不是原始数组。尝试使用 std::string
而不是原始字符串。尝试使用 std::ofstream
和 std::ifstream
而不是 C 的 FILE*
。如果您需要禁止具有相同帐号的两个帐户,则选择保证唯一元素的 C++ 容器。如果您需要在容器中查找元素,请尝试使用容器的成员函数进行搜索,如果该成员函数不存在,则使用标准 C++ 算法中的标准搜索函数。
无情地重复使用和窃取。
关于c++ - 通过 2 个文件匹配程序编写可读的名字和姓氏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5346949/