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

标签 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;
}

最佳答案

您使 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。

关于c++ - 为三个名称提示中的每一个在 C++ 中生成随机字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54950871/

相关文章:

c# - 关于生成无法追踪的发票 ID 的想法

c++ - 如何读取 beast::websocket 中错误请求的 header ?

C++ Enum in struct error for definition

c++ - 碰撞检测有效但有小故障?

php - 唯一ID的最佳方法(PHP + Mysql)

powershell - Powershell-数字格式显示错误的结果

c++ - -1 和 ~0 有什么区别

java - 使用 Mastermind 和 Random() 类上的 Mocks 进行单元测试

css - 语法错误 : error evaluating function `unit` : the first argument to unit must be a number

ios - 如何对NSString中的成分进行排序?例如1/2杯牛奶,1/4勺粉