How to automatically generate an ID based on time in C++?
In C++, you can use the time() function from the header file to get the current time and convert it into a string to use as an automatically generated ID. Here is an example code:
#include <iostream>
#include <ctime>
#include <sstream>
std::string generateUniqueID() {
std::time_t currentTime = std::time(nullptr);
std::stringstream ss;
ss << currentTime;
return ss.str();
}
int main() {
std::string uniqueID = generateUniqueID();
std::cout << "Generated Unique ID: " << uniqueID << std::endl;
return 0;
}
In the example above, the generateUniqueID() function takes the current time and converts it into a string to create a unique ID automatically. This function is then called in the main() function to output the generated unique ID.
Please note that the numbers generated by this method may not be entirely unique, as calling the time() function twice may return the same timestamp. If higher-level uniqueness is needed, consider adding more information such as a process ID or a random number.
More tutorials
How to check for listening ports in Linux?(Opens in a new browser tab)
Set in Python(Opens in a new browser tab)
Spring Component annotation(Opens in a new browser tab)
How to Maintain Updated Rocky Linux 9 Servers(Opens in a new browser tab)
Java’s Random Number Generator(Opens in a new browser tab)