【问题标题】:generating random characters in C++ for each of three prompts for name在 C++ 中为三个名称提示中的每一个生成随机字符
【发布时间】:2019-03-01 19:09:57
【问题描述】:

此程序提示用户输入名称。然后它将使用两个 while 循环。一个 while 循环生成 3 个随机字母,然后是一个破折号,然后是另一个 while 循环以生成 3 个随机数字。我可以根据需要让程序执行此操作 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;
}

【问题讨论】:

  • 不是问题,但您可以删除代码中的所有静态强制转换。 static_cast&lt;int&gt;('a') + rand() % (static_cast&lt;int&gt;('z') - static_cast&lt;int&gt;('a') + 1)'a' + rand() % ('z' - 'a' + 1) 完全相同。原因见:en.cppreference.com/w/c/language/…
  • 为什么要输入名字?为什么不把randomID打印出来再使用之前清除一下?
  • 这正是作业所需要的

标签: c++ random numbers srand


【解决方案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。

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 2013-01-19
    • 2019-08-17
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    相关资源
    最近更新 更多