如何让C++程序检测输入字符串中是否包含特定关键词?
C++聊天机器人关键词包含检测解决方案
1. 解决完整输入问题
你当前使用cin >> ans只能读取到第一个空格前的内容,比如输入"hello there"时,ans只会存储"hello",导致后续检测无法覆盖整句输入。要读取包含空格的整行内容,需要改用getline(cin, ans)。
2. 检测字符串中的关键词
C++的std::string类提供了find方法,可用于查找子字符串的位置:
- 若
ans.find("hello")的返回值不等于string::npos,则说明ans中包含"hello"关键词。
完整示例代码
#include <iostream> #include <string> using namespace std; int main() { string ans; cout << "Hello, I am Oliver, a Chatbot" << endl; cout << "What can I do for you today?" << endl; // 读取整行输入,包含空格 getline(cin, ans); // 检测是否包含"hello"关键词 if (ans.find("hello") != string::npos) { cout << "Hello to you too!" << endl; } else { cout << "I don't understand that." << endl; } return 0; }
进阶:忽略大小写匹配
如果需要识别"Hello"、"HELLO"这类不同大小写的输入,可以先把输入字符串统一转换为小写,再进行检测:
#include <iostream> #include <string> #include <cctype> // 用于tolower函数 using namespace std; int main() { string ans; cout << "Hello, I am Oliver, a Chatbot" << endl; cout << "What can I do for you today?" << endl; getline(cin, ans); // 将输入转换为全小写 for (char &c : ans) { c = tolower(static_cast<unsigned char>(c)); } if (ans.find("hello") != string::npos) { cout << "Hello to you too!" << endl; } else { cout << "I don't understand that." << endl; } return 0; }
内容的提问来源于stack exchange,提问作者bleachedb
相关产品推荐
相关产品推荐

