Hey, When i say right i mean is this the best way to do it. The program works fine and I just put it together in about one minute.

#include <iostream>

using namespace std;

int main()
{
    srand(time(NULL));
    
    const char* words[] = {"silly", "bafoon", "monkey"};
    int i = rand() % 3;
    
    cout << words[i];
            
    cin.get();
    
    return 0;
}

Dani AI

Generated

Nice and simple — ’s snippet does the job. is also right: some compilers need the proper C headers included, so for the C-style rand approach include <cstdlib> (for rand/srand) and <ctime> (for time). Seed only once at program start; seeding repeatedly makes the sequence less random.

For better quality and fewer gotchas use the C++11 <random> facilities instead: they avoid the modulo bias of rand() % n, give well-tested engines like std::mt19937, and provide std::uniform_int_distribution to pick indices correctly. See the standard notes on rand and the modern <random> utilities for details: rand, uniform_int_distribution, random_device.

Example (C++11 and later):

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

int main() {
    std::vector<std::string> words{"apple", "banana", "cherry"};
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<std::size_t> dist(0, words.size() - 1);
    std::cout << words[dist(gen)] << '\n';
}

If you must stick with rand() (pre-C++11), include <cstdlib> and <ctime>, compute the array length with sizeof(words)/sizeof(words[0]), and call srand once. Be aware rand() has poorer randomness and possible modulo bias; for anything beyond toy code, prefer <random>.

Recommended Answers

All 2 Replies

Seems to be good :)
Only problem I had was that I had to include <ctime> in order to compile it.

Oh Ok. I didn't need <ctime>. Thanks anyways

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.