Zay Eyes Zay Eyes - 3 months ago 48
C++ Question

AUTO GENERATE ID C++

I'm trying to have an auto generated ID in adding students.

So these are my problems:


  • If I display what has been added,
    ID_NUM
    's are all the same.

  • If I re-open the program, it should + 1 the last
    id_num
    that added.



But I don't know what I should do. :(

class moon
{

int id_num;
char name[100];
char course[100];
public:
void add;
}

void alt();

void alt()
{
system("cls");

char a;
moon min;
ofstream nimp;
nimp.open("HEALTH.DAT",ios::binary|ios::app);
min.add();
nimp.write(reinterpret_cast <char *> (&min), sizeof(moon));
cin.ignore();
cin.get();
heal.close();
id_num++;

}

void moon::add()
{

cout<<"ID NUMBER: "<<id_num<<endl;
cin.ignore();
cout<<"Enter course: ";
gets(course);
cout<<"Enter name: ";
gets(name);
}

Answer

Here's one way:

#include <fstream>
#include <iostream>

struct id_generator
{
    id_generator()
    : _id (0)
    {
        std::ifstream ifs("previous_id.txt");
        ifs >> _id;
    }

    ~id_generator()
    {
        std::ofstream ofs("previous_id.txt", std::ios_base::out | std::ios_base::trunc);
        ofs << _id;
    }

    int operator()() { return _id++; }

    int _id;
};

int main()
{
    id_generator idgen;

    std::cout << "next id is: " << idgen() << std::endl;
    std::cout << "next id is: " << idgen() << std::endl;

    return 0;
}

example of use:

$ c++ -o idgen idgen.cpp
$ idgen
next id is: 0
next id is: 1
$ idgen
next id is: 2
next id is: 3
Comments