Home > database >  C File How to auto generate number for next data to store
C File How to auto generate number for next data to store

Time:07-15

#include <iostream>
#include <fstream>

using namespace std;

class Customer {
    private:
        fstream database;
        string customerRecord = "customerRecord.txt";

        int movieID = 0;

    public:

        void write() {
            database.open(customerRecord, ios::app | ios::in);

            string lines;

            if(database.is_open()) {
                while(getline(database, lines)) {
                    movieID  ;
                }

                database << movieID   1 << endl;
            } else {
                cout << "Cannot open database." << endl;
            }
    }

};

int main() {
    Customer customer;

    customer.write();
}

Suppose that there is already an existing data which is 1 inside customerRecord.txt file

enter image description here

So in my line of code:

while(getline(database, lines)) {
    movieID  ;
}

database << movieID   1 << endl;

I read the total number of lines which is currently 1 and increment it by 1 which will be 2 that become the next auto generated ID for the next data that will be stored.

The problem is whenever I try to write a new data inside the file, it fails to write inside the file in which is I suppose that there is something wrong with my code below:

database << movieID   1 << endl;

CodePudding user response:

If to you read to the end of the file and stop reading because you tried to read past the end of the file, the fail bit and the eof bit are set and you cannot read or write until both are cleared.

The only way out of

while(getline(database, lines)) {
    movieID  ;
}

is to be unable to read any further and set fail and eof. So

while(getline(database, lines)) {
    movieID  ;
}
database.clear();
  • Related