gpt4 book ai didi

c++ - 如何用 C++ 编写基本的来回对话

转载 作者:行者123 更新时间:2023-11-28 04:33:24 25 4
gpt4 key购买 nike

我想编写一个允许用户和计算机之间来回通信的基本脚本。例如

USER: what's your name?
BOT: my name is John
USER: what's today's weather?
BOT: the weather is sunny

我目前的代码是...

#include <iostream>
#include <map>
#include <vector>
#include <string>

using namespace std;

string respond(map<string, vector<string> > responses, string message)
{
if(responses.find(message) != responses.end()){
return responses[message][0];
} else {
return responses["default"][0];
}
}

int main(){
map<string, vector<string> > responses;

vector<string> temp;
temp.push_back("my name is John");
temp.push_back("they call me John");
temp.push_back("I go by John");
responses["what's your name?"] = temp;

vector<string> temp1;
temp1.push_back("the weather is sunny");
temp1.push_back("it's cloudy today");
responses["what's today's weather?"] = temp1;

vector<string> temp2;
temp2.push_back("default message");
responses["default"] = temp2;

while(1){
cout << "Write your message to the bot and press ENTER" <<
endl;
string user_msg;
cout << "USER: ";
cin >> user_msg;
if(user_msg == "quit"){
break;
}
else{
string temp = respond(responses, user_msg);
cout << temp << endl;
}
}


return 0;
}

现在,当我输入其中一个 responses[](即 你叫什么名字?/今天天气如何?)时,我回来了……

Write your message to the bot and press ENER
USER: what's your name?
default message
Write your message to the bot and press ENER
USER: default message
Write your message to the bot and press ENER
USER: default message
Write your message to the bot and press ENER
USER:

如能帮助解决此问题,我们将不胜感激。谢谢

最佳答案

您输入的字符串不正确。在方法respond 中,message 的值就是what's。发生这种情况是因为您使用的 cin 在遇到空格后未读取输入。你可以使用类似 getline 的东西反而。

cout << "USER: ";
// Do this
std::getline (std::cin, user_msg);

这是您的代码的一个工作示例:http://cpp.sh/5dnrh

关于c++ - 如何用 C++ 编写基本的来回对话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52241735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com