C++ fill string with random uppercase letters

To fill a string with random uppercase letters in C++, you can follow these steps:

  1. Include the necessary header files:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
  1. Declare a constant variable to represent the length of the string:
const int STRING_LENGTH = 10;
  1. Create a function to generate a random uppercase letter:
char generateRandomUppercase() {
    return 'A' + rand() % 26;
}
  1. Initialize the random number generator:
srand(static_cast<unsigned int>(time(0)));
  1. Create an empty string to store the random letters:
std::string randomString;
  1. Use a loop to fill the string with random uppercase letters:
for (int i = 0; i < STRING_LENGTH; i++) {
    randomString += generateRandomUppercase();
}
  1. Print the resulting random string:
std::cout << randomString << std::endl;

The complete code will look like this:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

const int STRING_LENGTH = 10;

char generateRandomUppercase() {
    return 'A' + rand() % 26;
}

int main() {
    srand(static_cast<unsigned int>(time(0)));
    std::string randomString;

    for (int i = 0; i < STRING_LENGTH; i++) {
        randomString += generateRandomUppercase();
    }

    std::cout << randomString << std::endl;

    return 0;
}

This code generates a random string of uppercase letters with a length of 10 characters. The generateRandomUppercase function uses the rand() function to generate a random number between 0 and 25 and then adds it to the ASCII value of 'A' to obtain a random uppercase letter. The srand function is used to seed the random number generator based on the current time, ensuring different results each time the program is run. The resulting random string is stored in the randomString variable and printed to the console.