#include <iostream>
#include <string>
#include <map>
#include <fstream>
class ChatBot {
public:
void chat() {
loadKnowledgeBase();
std::cout << "你好!我是你的聊天机器人。你想和我聊些什么?" << std::endl;
while (true) {
std::cout << "你: ";
std::getline(std::cin, userInput);
if (userInput == "退出") {
saveKnowledgeBase();
std::cout << "聊天机器人: 再见!" << std::endl;
break;
}
std::cout << "聊天机器人: " << generateResponse(userInput) << std::endl;
}
}
private:
std::string userInput;
std::map<std::string, std::string> knowledgeBase;
void loadKnowledgeBase() {
std::ifstream file("knowledge_base.txt");
std::string input;
std::string response;
while (std::getline(file, input) && std::getline(file, response)) {
knowledgeBase[input] = response;
}
file.close();
}
void saveKnowledgeBase() {
std::ofstream file("knowledge_base.txt");
for (const auto& entry:knowledgeBase) {
file << entry.first << std::endl;
file << entry.second << std::endl;
}
file.close();
}
std::string generateResponse(const std::string& input) {
if (knowledgeBase.count(input) > 0) {
return knowledgeBase[input];
} else {
std::string response;
std::cout << "聊天机器人: 对不起,我不知道如何回答这个问题。请告诉我一个合适的回答:" << std::endl;
std::cout << "你: ";
std::getline(std::cin, response);
knowledgeBase[input] = response;
return response;
}
}
};
int main() {
ChatBot bot;
bot.chat();
return 0;
}
帮忙看一下,代码的问题出在哪儿了