Question

I would like to interleave a random number with some alphanumeric characters, for example: HELLO mixed with the random number 25635 → H2E5L6L3O5. I know %1d controls the spacing, although I'm not sure how to interleave text between the random numbers or how accomplish this.

Code:

int main(void) {
    int i;

    srand(time(NULL));
    for (i = 1; i <= 10; i++) {

        printf("%1d", 0 + (rand() % 10)); 

        if (i % 5 == 0) {
            printf("\n");
        }
    }
    return 0;
}

btw - if my random number generator isn't very good i'm open to suggestions - thanks

Was it helpful?

Solution

If you're okay with using C++11, you could use something like this:

#include <iostream>
#include <random>
#include <string>

int main() {
    std::random_device rd;
    std::default_random_engine e1(rd());
    std::uniform_int_distribution<int> uniform_dist(0, 9);

    std::string word = "HELLO";
    for (auto ch : word) {
        std::cout << ch << uniform_dist(e1);
    }
    std::cout << '\n';
}

...which produces e.g.:

H3E6L6L1O5

If you're stuck with an older compiler, you could use rand and srand from the standard C library for your random numbers:

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

int main() {
    std::srand(std::time(NULL));

    std::string word = "HELLO";
    for (int i = 0; i < word.size(); ++i) {
        std::cout << word[i] << (rand() % 10);
    }
    std::cout << '\n';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top