Search code examples
c++randomnumberssrand

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


This program prompts the user to enter in a name. It will then use two while loops. One while loop to generate 3 random letters, followed by a dash followed by another while loop to generate the 3 random digits. I can get the program to do this three times as required.

The problem is it will generate the same three random numbers and letters for each of the three names entered. I would like each name entered to print a unique set of letters and numbers. Is it something with the srand() function?

There is also the problem of adding the dash after printing the characters after the second name is entered and two dashes after printing the characters for the third name entered.

#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;
}

Solution

  • You make randomID empty, set numberOfCharacters to zero, and set numberOfNumbers to zero only once outside the loop. Instead, do this:

    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: ";
        ...
    

    Also:

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

    I don't think one minus nine is what you want. Try swapping the 1 and the 9.