C++ 聊天机器人:基于字符匹配的问答系统
以下是一个简单的 C++ 聊天机器人的示例代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 问题-回答的结构体
struct QA {
string question;
string answer;
};
int main() {
// 预设的问题与回答
vector<QA> qas = {
{"你好", "你好呀"},
{"你叫什么名字", "我是聊天机器人"},
{"你喜欢做什么", "我喜欢和人类聊天"},
{"再见", "再见,祝你有美好的一天"}
};
// 提示用户输入问题
cout << "你可以问我一些问题:" << endl;
while (true) {
string userQuestion;
getline(cin, userQuestion); // 获取用户输入的问题
// 寻找与用户输入的问题字符匹配程度最高的问题
int maxMatch = 0;
string bestAnswer;
for (const auto& qa : qas) {
int match = 0;
for (int i = 0; i < qa.question.length(); i++) {
if (tolower(qa.question[i]) == tolower(userQuestion[i])) {
match++;
}
}
if (match > maxMatch) {
maxMatch = match;
bestAnswer = qa.answer;
}
}
cout << "回答:" << bestAnswer << endl;
}
return 0;
}
这个聊天机器人通过遍历预设的问题与回答,寻找与用户输入的问题字符匹配程度最高的问题,并输出相应的回答。注意,该示例只是一个简单的实现,可以根据需要进行进一步的扩展和改进。
原文地址: http://www.cveoy.top/t/topic/nK4 著作权归作者所有。请勿转载和采集!