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

时间:2019-03-01 19:09:57

标签: c++ random numbers srand

此程序提示用户输入名称。然后它将使用两个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;
}

1 个答案:

答案 0 :(得分:1)

您将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。尝试交换1和9。