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";
}
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.
#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_searchif( std::regex_search( sentence, fox_re ) )
std::cout << "found the word 'fox' in sentence '" << sentence << "'\n" ;
}