用C++实现以上代码
时间: 2023-12-14 17:37:46 浏览: 26
以下是用C++实现的代码:
```c++
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<string> greetings = {"Hello", "Hi", "Hey", "What's up"};
vector<string> topics = {"weather", "sports", "movies", "music"};
cout << "Bot: " << greetings[rand() % greetings.size()] << endl;
while (true) {
string user_input;
cout << "You: ";
getline(cin, user_input);
transform(user_input.begin(), user_input.end(), user_input.begin(), ::tolower);
if (user_input == "goodbye" || user_input == "bye") {
cout << "Bot: Goodbye!" << endl;
break;
}
bool topic_found = false;
for (auto& topic : topics) {
if (user_input.find(topic) != string::npos) {
cout << "Bot: Let's talk about " << topic << endl;
topic_found = true;
break;
}
}
if (!topic_found) {
cout << "Bot: I'm sorry, I didn't understand." << endl;
}
}
return 0;
}
```
这段代码与之前的Python代码实现类似,使用向量来存储问候语和主题,使用随机数来选择问候语。在while循环中,获取用户输入并将其转换为小写字母,然后检查用户是否想要结束对话。如果是,则输出“Goodbye!”并退出循环。否则,遍历主题向量,查找用户输入中是否包含主题单词。如果找到,则输出相应的主题。如果没有找到,则输出“我不理解”。