为三个名称提示中的每一个在 C++ 中生成随机字符

generating random characters in C++ for each of three prompts for name

此程序提示用户输入名称。然后它将使用两个 while 循环。一个 while 循环生成 3 个随机字母,然后是破折号,然后是另一个 while 循环以生成 3 个随机数字。我可以让程序根据需要执行三次。

问题是它会为输入的三个名字中的每一个生成相同的三个随机数字和字母。我希望输入的每个名称都打印出一组独特的字母和数字。是srand()函数的问题吗?

还有输入第二个名字后打印字符后添加破折号和输入第三个名字后打印字符后添加两个破折号的问题。

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    int nameCount = 0;          // Hold the number of names entered by user
    string randomID;            // Used to concatenate the random ID for 3 names
    string name;                // To hold the 3 names entered by the user
    int numberOfCharacters = 0;
    int numberOfNumbers = 0;
    int a;
    srand(time(NULL));
    while(nameCount < 3) {
        cout << "\nEnter a name: ";
        getline(cin, name);
        while (numberOfCharacters < 3) {
            randomID += static_cast<int>('a') + rand() % 
                (static_cast<int>('z') - static_cast<int>('a') + 1);
            numberOfCharacters++;
        }
        randomID += "-";
        while (numberOfNumbers < 3) {
            randomID += static_cast<int>('1') + rand() %
                (static_cast<int>('1') - static_cast<int>('9') + 1);
            numberOfNumbers++;
        }
        cout << randomID;
        nameCount++;
    }
    return 0;
}

您使 randomID 为空,将 numberOfCharacters 设置为零,并且仅在循环外将 numberOfNumbers 设置为零一次。相反,这样做:

int main() {
    int nameCount = 0;          // Hold the number of names entered by user
    string name;                // To hold the 3 names entered by the user
    int a;
    srand(time(NULL));
    while(nameCount < 3) {
        string randomID;            // Used to concatenate the random ID for 3 names
        int numberOfCharacters = 0;
        int numberOfNumbers = 0;
        cout << "\nEnter a name: ";
    ...

还有:

        randomID += static_cast<int>('1') + rand() %
            (static_cast<int>('1') - static_cast<int>('9') + 1);

我不认为一减九是你想要的。尝试交换 1 和 9。