如何使用inFile编写和检索多个记录?

时间:2017-11-20 21:47:18

标签: c++ file-io save

我有一个家庭作业,我必须存储停车票信息并检索数据。所以我认为将信息存储到txt文件会更容易:

void v_input(string ticket, string f_name, string l_name, string address, 
string city, string plate, string vin, string violation, string v_code, 
double amount, double l_fee, string make, string model, bool paid, int date, 
int time, int payby, int officer_no) 

{

ofstream inFile;
inFile.open("tickets.txt");
if (inFile.is_open()) {

inFile << ticket << "\n" << f_name << "\n" << l_name << "\n" << address << "\n" << city << "\n" << plate << "\n"
<< vin << "\n" << violation << "\n" << v_code << "\n" << amount << "\n" << l_fee << "\n" << make << "\n" << model
<< "\n" << paid << "\n" << date << "\n" << time << "\n" << payby << "\n" << officer_no << "\n" << endl;

}

    //Check for Error

if (inFile.fail()) {

cout << "tickets.txt is Corrupted" << endl;
exit(1);

}

这很好用,除了它似乎覆盖了文件。我真正想要的是每次添加一个单独的记录(没有覆盖)程序运行。

此外,我需要设法搜索每个单独的记录。这就是我到目前为止所做的:

void plate_search() {

string search;
string line;

ifstream inFile;
inFile.open("tickets.txt");

if (!inFile) {
    cout << "Unable to open file" << endl;
    exit(1);
}

cout << "Please enter a plate Number to search : " << endl;
cin >> search;

size_t pos;
while (inFile.good())
{
    getline(inFile, line); // get line from file
    pos = line.find(search); // search
    if (pos != string::npos) // string::npos is returned if string is not 
found
    {
        cout << "Found!";
        break;
    }
}

正如您所看到的那样,它只是一般搜索,它会将搜索参数中的所有内容都拉出来。

我需要做的是让它将每个条目识别为单独的记录并提取这些特定的故障单。我可以通过添加一个特定的标记来表示一条记录的结尾(即每条记录应以####结尾),但我不确定如何实现它?

Q1:我怎么能让inFile将单独的记录写入txt文件而不是覆盖它们?

Q2:我如何将搜索查询缩小到单独的记录?

0 个答案:

没有答案