Computer >> Máy Tính >  >> Lập trình >> C ++

Làm cách nào để tạo một chuỗi chữ-số ngẫu nhiên bằng C ++?

Trong phần này, chúng ta sẽ xem cách tạo một chuỗi chữ và số ngẫu nhiên bằng C ++. Ở đây chúng tôi đang cung cấp các chữ cái thường, chữ hoa và số (0-9). Chương trình này lấy các ký tự ngẫu nhiên, sau đó tạo chuỗi ngẫu nhiên.

Input: Here we are giving the string length
Output: A random string of that length. Example “XSme6VAsvJ”

Thuật toán

Step 1:Define array to hold all uppercase, lowercase letters and numbers
Step 2: Take length n from user
Step 3: Randomly choose characters’ n times and create a string of length n
Step 4: End

Mã mẫu

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz";
int len = sizeof(alphanum) - 1;
char genRandom() { // Random string generator function.
   return alphanum[rand() % len];
}
int main() {
   srand(time(0));
   int n;
   cout << "Enter string length: ";
   cin >> n;
   for(int z = 0; z < n; z++) {    //generate string of length n
      cout << genRandom(); //get random character from the given list
   }
   return 0;
}

Đầu ra

Enter string length: 10
XSme6VAsvJ