选择两个字符串中的一个来输出?

时间:2015-11-04 04:44:27

标签: c++

我想知道如何让程序随机输出两个字符串中的一个。 很难解释,但这是我的例子:

#include <iostream>
#include <string>
using namespace std;

int main()
{
string age;

cout << "How old are you?" << endl;
cin >> age;

if (age < 0)
{
cout << "Invalid age" << endl;
}
     if (0 >= age && age <<= 3)
     {
     cout << "Oh you're just a baby" << endl;
     //               OR (random)
     cout << "Time to take a nap!" << endl;
     }

return 0;
}

我想编制输出“哦,你只是个孩子”或“时间小睡!”当用户输入0到3之间的数字时,随机可以解释。

3 个答案:

答案 0 :(得分:1)

尝试:

#include <cstdlib>
...
...
...
/* initialize random seed: */
srand(time(NULL));

/* generate secret number: */
int ss = rand() % 2;
if (ss) {
    cout << "Oh you're just a baby" << endl;
} else {
    cout << "Time to take a nap!" << endl;
}

答案 1 :(得分:1)

你也可以试试这个:

从用户那里获取输入并将其与随机生成的值进行比较并根据它输出打印输出:

#include <iostream>
using namespace std;

int main()
{
int age;

srand(time(NULL));
int a = rand()%3;
cout<<a<<endl;   // print the random generated number (between 0 and 3 )
cout << "How old are you?" << endl;
cin >> age;

if (age < 0)
{
    cout << "Invalid age" << endl;

}

if(age == a){
    cout << "Oh you're just a baby" << endl;
}else{
    cout << "Time to take a nap!" << endl;
}


    return 0;
}

答案 2 :(得分:1)

这使用STL并且只从表中随机选择,没有任何用户输入:

#include <array>
#include <chrono>
#include <cstddef>
#include <iostream>
#include <random>

using std::cout;
using std::endl;

int main(void) {
  // The size of the table:
  constexpr size_t n = 2;
  // A table of insults:
  constexpr std::array<const char*, n> insults = {
    "Oh, you're just a baby!",
    "Time to take a nap."
  };

  // Boilerplate to initialize a RNG:
  const std::default_random_engine::result_type seed = std::chrono::system_clock::now().time_since_epoch().count();
  std::default_random_engine generator (seed);
  // Generate a random index into the string table:
  std::uniform_int_distribution<size_t> distribution(0, n-1);

  // A random number from distribution:
  const size_t x = distribution(generator);
  // Our random string:
  const char* const s = insults[x];

  cout << s << endl;

  return EXIT_SUCCESS;
}