[英]C++ How can I scan the user's string input for a specific word/words?
#include <regex>
#include <string>
#include <iostream>
int main()
{
using namespace std;
string sentence;
cin >> sentence;
string word = "banana";
regex r("\\b" + word + "\\b");
smatch s;
if (regex_search(sentence, s, r)) {
cout << "success" << endl;
}
}
I got this to partially work. 我得到了部分工作。 I type in a sentence that includes the word banana, and here comes the problem.
我输入一个包含香蕉一词的句子,这就是问题所在。 If I type banana as the first word in my sentence it will detect it(example: banana etc), but if it's not the first word (example: etc banana) it will not detect it.
如果我在句子中输入“ banana”作为第一个单词,它将检测到它(例如:banana等),但是如果不是第一个单词(例如:“ banana”等),它将不会检测到它。 Is there a fix for it?
有解决办法吗? and yes, I am using namespace because it makes my life easier.
是的,我使用名称空间是因为它使我的生活更轻松。
"I type in a sentence that includes the word banana, and here comes the problem. If I type banana as the first word in my sentence it will detect it(example: banana etc), but if it's not the first word (example: etc banana) it will not detect it."
“我输入一个包含香蕉一词的句子,这就出现了问题。如果我将香蕉作为我的句子的第一个单词 ,它将检测到它(例如:banana等),但如果不是第一个单词(例如:等香蕉),它将无法检测到。”
The code as you have it 拥有的代码
std::cin >> sentence;
only reads a single word from input (up to the next whitespace delimiter). 仅从输入中读取单个单词(直到下一个空格分隔符)。
"Is there a fix for it?"
“有解决办法吗?”
Of course: If you want to get a whole sentence from input, you rather use 当然:如果您想从输入中获取整个句子,则可以使用
std::getline(std::cin,sentence);
Also note, using std::regex()
for such a simple case is much too heavy. 还要注意,在这种简单情况下使用
std::regex()
实在太繁琐了。 If you really only want to look up simple sequences like "banana"
and not patterns, std::string::find()
, will serve you well (at much less cost). 如果您真的只想查找诸如
"banana"
类的简单序列而不是模式,则std::string::find()
会很好地为您服务(成本要低得多)。
"and yes, I am using namespace because it makes my life easier."
“是的,我正在使用名称空间,因为它使我的生活更轻松。”
In the end it won't make your life easier, but just the opposite. 最后,它不会使您的生活更轻松,而相反。 You are just prone to make collisions with the
std
namespace in your code (think for example about user defined functions for min()
, max()
, swap()
, etc). 您很容易在代码中与
std
名称空间发生冲突(例如,考虑一下min()
, max()
, swap()
等用户定义的函数)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.