Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

C++ Program: สุ่มตัวอักษรภาษาอังกฤษ (Random Alphabets)

สร้างสตริงสุ่มของตัวอักษร a-z ความยาว n

ตัวอย่างโค้ด

#include <bits/stdc++.h>
using namespace std;

const int MAX = 26;

string gen_random(int n) {
    char alphabet[MAX] = {
        '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'
    };
    string res = "";
    for (int i = 0; i < n; i++)
        res += alphabet[rand() % MAX];
    return res;
}

int main() {
    srand(time(NULL)); // Seed ด้วยเวลา
    int n = 7;
    cout << gen_random(n) << endl;
    return 0;
}

ผลลัพธ์ (ตัวอย่าง)

gwqrgpa

ปรับปรุงด้วย C++11 (แนะนำ)

#include 
#include 

string gen_random_modern(int n) {
    static std::mt19937 rng(std::random_device{}());
    static std::uniform_int_distribution dist(0, 25);
    const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    string res;
    res.reserve(n);
    for (int i = 0; i < n; i++)
        res += alphabet[dist(rng)];
    return res;
}

ขยาย: รวมตัวใหญ่และตัวเลข

const char charset[] = 
    "abcdefghijklmnopqrstuvwxyz"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "0123456789";
uniform_int_distribution dist(0, sizeof(charset)-2);