我只是想知道如何才能做到这一点。以下是我想要的代码片段:
/**< CASPOR's question script */
if (input == "N")
{
cout << "Ok, " << name << " would you like to ask me a simple question?\n";
cin >> input;
{
if (input == "Y")
{
while ("Y")
{
cout << "Ask away!\n";
cin.ignore();
getline(cin, input);
{
if (input == "Who are you?")
{
cout << "I am CASPOR, or a C++ Automated Speech Program Of Recognition.\n";
}
if (input == "What is your purpose?")
{
cout << "My purpose is to entertain and amaze. Almost like a boredom breaker.\n";
}
if (input == "What can you do?")
{
cout << "I can do anything the developers program me to do!";
}
cout << "Would you like to ask another question?\n";
cin >> input;
{
if (input == "Y")
continue;
}
}
}
}
}
}
在"CASPOR"
回答你的问题的地方,我怎么能有机会每次都说些不同的东西?
答案 0 :(得分:1)
您可以将答案存储在容器中(通常为std::vector<std::string>>
)并使用std::shuffle
将其随机化。
然后只需在矢量中选择第一个答案。
示例:强>
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <random>
#include <chrono>
int main()
{
// Initialize the seed
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
// Store the answers
std::vector<std::string> answers = { "Answer1" , "Answer2", "Answer3", "Answer4" };
for(std::size_t n = 0 ; n <10 ; ++n)
{
// Randomize the vector
std::shuffle(std::begin(answers), std::end(answers), std::default_random_engine(seed));
std::cout << answers[0] << '\n';
}
}
备注:强>
if
应为if ... else if ... else if ...
while ("Y")
毫无意义,只需while(true)
答案 1 :(得分:0)
你会有类似的东西:
std::string possibleAnswers[] = {"Answer 1", "Answer 2", "Answer 3", "etc."};
然后可能做类似的事情:
std::cout << possibleAnswers[rand() % numPossibleAnswers] << "\n";
这是基本的东西,但是如果你想要更复杂的东西,你可以设置一个系统,从.csv加载答案,其中每一行都有可能回答不同的问题。
答案 2 :(得分:0)
这是一个在预定义字符串向量上使用<random>
的小例子:
default_random_engine my_random; // random generator but not yet seeded -> so always the same numbers
my_random.seed(time(NULL)); // intiialisze with at least a little bit of randomness
vector<string> sentences = { "Hello", "Hi !", "Happy to see you !", "etc..." };
uniform_int_distribution<int> sentences_dist(0, sentences.size()-1); // uniform distribution between 0 and size of vector (equal proba to have any of it)
for (int i = 0; i < 15; i++)
cout << sentences[sentences_dist(my_random)] << endl;
答案 3 :(得分:0)
你可以创建一个问题数据库并编写一个函数,在它被唤起时它会返回一个随机问题,如下例所示:
#include <iostream>
#include <random>
#include <array>
#include <string>
std::array<std::string, 3> questions {"Who are you?", "What is your purpose?", "What can you do?"};
std::string random_question() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, questions.size() - 1);
return questions[dis(gen)];
}
int main() {
for(int n = 0; n < 10; ++n) std::cout << random_question() << std::endl;
}