Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update GenerateRandomString.cpp #189

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 26 additions & 14 deletions GenerateRandomString.cpp
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
#include <iostream>
#include <cstdlib>
#include <cstdlib>
#include <ctime>
#include <string>

using namespace std;
// Function to generate a random string of a specified length
std::string generateRandomString(int length) {
const std::string characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789";
std::string randomString;

string generateRandomString(int length) {
const string characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789";
string randomString;
// Check for valid input
if (length <= 0) {
throw std::invalid_argument("Length should be a positive integer.");
}

// Generate random characters
for (int i = 0; i < length; ++i) {
Expand All @@ -24,21 +28,29 @@ int main() {
int length;

// Seed the random number generator
srand(static_cast<unsigned int>(time(0)));
std::srand(static_cast<unsigned int>(std::time(0)));

// Take input for the length of the random string
cout << "Enter the length of the random string: ";
cin >> length;
std::cout << "Enter the length of the random string: ";
if (!(std::cin >> length)) {
std::cerr << "Invalid input. Please enter a positive integer." << std::endl;
return 1;
}

// Check for valid input
if (length <= 0) {
cout << "Length should be a positive integer." << endl;
std::cerr << "Length should be a positive integer." << std::endl;
return 1;
}

// Generate and display the random string
string randomString = generateRandomString(length);
cout << "Random String: " << randomString << endl;
try {
// Generate and display the random string
std::string randomString = generateRandomString(length);
std::cout << "Random String: " << randomString << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}

return 0;
}