Мне было просто интересно, как я мог это сделать. Вот фрагмент кода, в котором я хочу это:
/**< 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"
отвечает на ваши вопросы, как я могу включить шанс, что он будет говорить что-то другое каждый раз?
Вы можете хранить свои ответы в контейнере (обычно 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)
у вас было бы что-то вроде:
std::string possibleAnswers[] = {"Answer 1", "Answer 2", "Answer 3", "etc."};
Тогда, возможно, сделать что-то вроде:
std::cout << possibleAnswers[rand() % numPossibleAnswers] << "\n";
Это что-то базовое, но если вы хотите что-то более сложное, вы можете настроить систему, которая загружает ответы из .csv, где каждая строка имеет возможные ответы на свой вопрос.
Вот небольшой пример использования <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;
Вы можете создать базу данных вопросов и закодировать функцию, которая после ее вызова возвращает случайный вопрос, как в примере ниже:
#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;
}