-3

//for example, what code would I use to make wordone output one of four words randomly

cout<< " Once apon a time there was a "<< wordone << " who wanted to "<

2 Answers2

1

Assign wordone a random value beforehand. For instance,

switch(rand() % 4) {
    case 0: wordone = "foo"; break;
    case 1: wordone = "bar"; break;
    case 2: wordone = "ni";  break;
    default: wordone = "knight"; break;
}

Of course, the random number generator should be seeded (see the example on this page), and wordone should be declared (I managed to make it work as a std::string, but if you haven't learned that, then you can use char *).

John Perry
  • 2,497
  • 2
  • 19
  • 28
  • 1
    This works well, but depending on your use case, [`std::uniform_int_distribution` should be preferred](https://stackoverflow.com/a/32860886/1753435). Side note: Don't use `char *` for strings in C++. If you reall have to, use at least a `const char*`! – andreee Jun 18 '18 at 05:39
  • @andreee I agree, but I assume this is a programming assignment, and I've seen introductory texts that still start students off with `char *`, so I offered an alternative that the questioner could actually use. I don't remember `const char *` in such cases, but generally I'm working with students of my own who are taking first-year CS courses. It's a bit surprising to me that at least one first-year CS course hasn't been updated at least to C++11: it's as if the faculty **want** the students to learn bad programming techniques. – John Perry Jun 18 '18 at 05:41
0

Put the words in an array of strings.

Then use e.g. std::uniform_int_distribution to get a number between 0 and 3 (inclusive) as index into the array, and use that string.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • what u talk about . i think u can write some codes . or u can watch Learn more about formatting – 許維德 Jun 18 '18 at 08:29
  • 2
    @許維德 My goal is not to teach copy-paste programming. My goal is to make people do some research, and learn how to think for themselves. Now, you made your point, please stop pestering me. – Some programmer dude Jun 18 '18 at 08:51
  • i think u copy too.please stop pestering me. that i want to say .u vote -12 bad question to me. and 4 my questions u talk garbage word to me . – 許維德 Jun 18 '18 at 09:06