Auto generate id

Auto generate id

1
2
3
4
5
  Hello everyone !
I'm new here.
I'm trying to auto generate unique id for every patient who register in hospital management system.
So kindly help me with that.
Thank you so much. 
Something like this, perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>

struct patient {

    std::string name ;
    // ...

    unsigned long long id = ++last_assigned_id ;

    static unsigned long long last_assigned_id ;
};

unsigned long long patient::last_assigned_id = 1000 ;

int main()
{
    const patient some_patients[] = { { "tom" }, { "dick" }, { "harry" } } ;

    for( const patient& p : some_patients )
        std::cout << p.id << ". " << p.name << '\n' ;
}

http://coliru.stacked-crooked.com/a/d51ae5272b163bbe
Thanks JLBorges it helped me
But the problem is I need to apply this in File Handling where it should read the file and increment id by 1 each time when new patient is added.
Hi, umairbilal. If you can, speak by code: your question is not clear. JLBorges’s solution is a generic one: it fits nearly everywhere. Please, post a compilable example of what you’re trying to do to get better answers.

…in File Handling where it should read the file and increment id by 1 each time when new patient is added.

When you read a file, you do not add data; if you’re adding data, you’re writing into the file. Please explain.

And please specify if it is an assignment (I presume it is).
> read the file and increment id by 1 each time when new patient is added.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <string>
#include <fstream>

struct patient {

    std::string name ;
    // ...

    unsigned long long id = next_id() ;

    // path to file to store the last generated id
    static constexpr char id_file_name[] = "last_generated_unique_id.txt" ;

    static unsigned long long next_id( unsigned long long default_id = 1001 ) {
        
        unsigned long long id ;

        {
            // try to read from the last id from file;
            // if successful, increment the id to get the next unique id
            // otherwise, fall back to the default id 
            // (robust error reporting/handling elided for brevity)
            std::ifstream file(id_file_name) ;
            if( file >> id ) ++id ;
            else id = default_id ;
        }

        // update the file with the freshly generated id
        // (error handling elided for brevity)
        std::ofstream(id_file_name) << id << '\n' ;

        return id ;
    }
};
Thank you so much
You people are very helping and very nice people .
I got my problem solved.
Enoizat , yes it was an assignment.
😇😇😊😊
Topic archived. No new replies allowed.