How to Generate 6 Digit Random Number C++?

Hello Friends Today, through this tutorial, I will tell you how to generate a 6 digit Unique random number in C++.

Here are two ways to generate a 6-digit random number in C++:

Using `rand()` and string manipulation.

#include <iostream>
#include <cstdlib>
#include <string>

int main() {
// Seed the random number generator (optional for better randomness)
srand(time(0));

// Generate a random integer between 100000 and 999999 (inclusive)
int randomNumber = rand() % 900000 + 100000;

// Convert the integer to a string
std::string stringNumber = std::to_string(randomNumber);

// Ensure the string has 6 digits by prepending leading zeros if necessary
std::string paddedNumber = stringNumber.insert(0, 6 - stringNumber.length(), '0');

// Print the generated 6-digit number
std::cout << "Generated 6-digit number: " << paddedNumber << std::endl;

return 0;
}

Explanation:-

1. Header inclusions:-
– `<iostream>` for input/output operations (cout)
– `<cstdlib>` for random number generation (rand) and seeding (srand)
– `<string>` for string manipulation

2. Seeding the random number generator (optional):-
– `srand(time(0))` sets the seed for the random number generator using the current time. This helps improve the randomness of the generated number.

3. Generate a random integer:-
– `rand()` generates a pseudo-random integer between 0 (inclusive) and `RAND_MAX` (exclusive).
– We use the modulo operator (`%`) with 900000 to get a number within the range 0 to 899999.
– Adding 100000 ensures the final number is within the desired range of 100000 to 999999.

4. Convert to string:-
– `std::to_string(randomNumber)` converts the integer to a string representation.

5. Ensure 6 digits:-
– `stringNumber.insert(0, 6 – stringNumber.length(), ‘0’)` inserts leading zeros to the string if it has less than 6 digits.

6. Print the result:-
– `std::cout << “Generated 6-digit number: ” << paddedNumber << std::endl;` prints the generated 6-digit number to the console.