如何修改C++代码生成8-16位随机字母组合名称?
Adjusting Random Name Length to 8-16 Characters in C++
Hey there! The fix here is straightforward—we just need to replace the fixed 12-length loop with random lengths between 8 and 16 for both the first and last names. Here's how to do it step by step:
Key Changes:
- Generate a random length for each name (8 to 16 inclusive) using
rand() - Adjust the loop iterations to match these random lengths
Modified Code
Here's your updated code with the length logic adjusted:
#include <iostream> #include <ctime> #include <string> // Added this header explicitly for std::string using namespace std; void genID(char letters[26]); int main() { srand(time(0)); // Seed random number generator once at program start char letters[26] = {'a', 'b' ,'c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; genID(letters); } void genID(char letters[26]) { string firstTemp, lastTemp; // Generate random lengths between 8 and 16 (inclusive) int firstLength = rand() % 9 + 8; // rand()%9 gives 0-8, +8 shifts range to 8-16 int lastLength = rand() % 9 + 8; // Build first name with random length for(int i = 0; i < firstLength; i++) { firstTemp += letters[rand() % 26]; } // Build last name with random length for(int i = 0; i < lastLength; i++) { lastTemp += letters[rand() % 26]; } // Your existing print logic goes here (example included) cout << "Generated First Name: " << firstTemp << endl; cout << "Generated Last Name: " << lastTemp << endl; }
Notes:
- I added
#include <string>since you're usingstd::string—your original code might have compiled by accident, but it's good practice to include necessary headers explicitly. - Using
+=instead offirstTemp = firstTemp + ...is more efficient for string concatenation. - Each name will have an independent random length between 8 and 16 characters, so they won't always be the same length.
内容的提问来源于stack exchange,提问作者PapaBlank
相关产品推荐
相关产品推荐

