Check a string input for specific input

I would like to have a user input a string, then search the string for a key word(s) and if it has those words output the statement.

example...


computer: Enter a sentence:

user: The fox is brown.

computer: *search for fox*
computer: *I found the word fox, let me tell you the sentence*

computer: The fox is brown.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  std::string userInput;
  std::cout<<"Enter a sentence: \n";
  std::cin>>userInput;

// search the input for word. How do I Do this Part? 

if (word is there)
{
//output sentence, Also How do I get the sentence to keep the spaces, instead of smashing into one long word?
std::cout<< userInput;
}
else
{
std::cout << "word is not here";
}

Last edited on
First this: std::cin>>userInput; will only input a single word. If you want a sentence you should look at using getline() instead.

Second what is this: std::userInput;? Perhaps you meant std::string userInput;?

Third you may want to look into some of the std::string.find() functions to see if your "word" is inside the string.


something like this:

string s= "the foxy wench";
size_t r = s.find("fox", 0);
if(r != string::npos) cout << "found";
else cout << "not found";

the << operations eat white space. use getline if you want a line that has words with spaces. but you need to read up on mixing << and getline both together, or only use one of the two.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <regex>

int main()
{
    std::string sentence ;
    std::cout << "Enter a sentence: " ;

    // read characters in a line of input (including white space) into the string
    std::getline( std::cin, sentence ) ;

    // search for the word 'fox'
    const std::string word = "fox" ;

    // regular expression: https://en.wikipedia.org/wiki/Regular_expression
    // (?:^|\\s+) : either beginning of string or one or more white space
    // word : the characters in the string (icase: ignoring case)
    // ?:$|\\s+ : either end of string or one or more white space
    const std::regex fox_re( "(?:^|\\s+)" + word + "(?:$|\\s+)", std::regex_constants::icase ) ;

    // https://en.cppreference.com/w/cpp/regex/regex_search
    if( std::regex_search( sentence, fox_re ) )
        std::cout << "found the word 'fox' in sentence '" << sentence << "'\n" ;
}
Topic archived. No new replies allowed.