【发布时间】:2017-01-24 21:29:08
【问题描述】:
你好,我做了一个程序,在我的程序中我有一个类 Customer。 为了将客户保存在计算机上,我创建了一个文件并用 ::like name::password::phonenbr 分隔客户的每个数据。但是我的问题是,如果我在代码的注释中写入行,数据将保存到文件中,但是如果我在 if() 中写入同一行来检查文件是否为空,则不会做任何事情,尽管我在编译器中看到这一行没有问题。
如果你能帮助我,那将是优雅的!
void Shop::Add_Customer()
{
fstream myfile; myfile.open("CustomerFile.txt");
string name, password, phonenbr;
string buffer, delimitor = "::";
system("cls");
cout << "Name of the customer: "; cin >> name;
cout << "Password of the customer: "; cin >> password;
cout << "Phone number of the customer: "; cin >> phonenbr;
if (!myfile.is_open())
{
myfile.open("CustomerFile.txt", ios::out);
}
//myfile << name + delimitor + password + delimitor + phonenbr << endl;
if (myfile.peek() == std::ifstream::traits_type::eof())
{
myfile << name + delimitor + password + delimitor + phonenbr << endl;
}
else
{
while (getline(myfile, buffer))
{
if (CheckIfCustomerExist(buffer, name, phonenbr) == true)
{
cout << "Customer already exist" << endl;
}
else
{
myfile << name + delimitor + password + delimitor + phonenbr << endl;
cout << "Customer insert in the file " << endl;
}
}
}
}
【问题讨论】:
-
离题:您会发现编写解析器以使用单个字符分隔符读回文件要容易得多。