简体   繁体   中英

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. 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."

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. 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).


"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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM