find a word in a string array sentence

We have to make a program where you ask the user to input a sentence and a word. Then, the program will check if the word is in the sentence. If it is, it will say, "word is in the sentence", if not, it will show, "word is not in the sentence".
So, what have you written so far?
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
26
27
28
#include <iostream>
#include <string>
#include <algorithm>

bool in_quote(const std::string& cont, const std::string& s)
{
    return std::search(cont.begin(), cont.end(), s.begin(), s.end()) != cont.end();
}

int main()
{
    std::string sentence, word;

    std::cout << "Enter sentence:"<< std::endl;
    std::getline(std::cin, sentence);


    std::cout << "Enter word to serch for:"<< std::endl;
    std::cin >> word;

    if (in_quote(sentence, word))
        std::cout << "word is in the sentence";
    else
        std::cout << "word is not in the sentence";
    std::cout << std::endl;

    return 0;
}
@MiiNiPaa, please do not provide whole solutions to homework problems for other people. They are taking the class to learn how to program, not to learn how to cheat. Your solution is also incorrect.
By the way the solution is incorrect because it checks the presence of some sequence of letters not a word. For example this sttement

"This does not work"

has no word "is" but the solution returns true.:)
Last edited on
I think a for loop with a break to escape out if the word is not a match, nested inside a do while loop would probably work. The trick, as was pointed out by L B and vlad from moscow is that you could find a word within a word. I think the solution would be to look for a space to begin the word (represented by ' ') and then make a condition that once you find the whole word, it must be followed by either a ' ' or a '.', '!', '?', etc. If it starts with a space and ends with a space or a sentence ending character, then it's a match. Hope that helps.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sent, word;
int i;
cout << "Input sentence" << endl;
std::getline(cin, sent);
cout << "Input word" << endl;
cin >> word;
unsigned found=word.find(sent);
if(found!=std::string::npos)
{std::cout << "word is in the sentence";}
else
{std::cout << "word is not in the sentence";}
system("pause");
return 0;
}




I tried this but the output keeps saying the word is in the sentence although it's not.
randisking, thanks!!! I'll try that.
Also keep in mind that if a word starts the very first word of the sentence won't have anything in front of it. An easy way to deal with that is if it's the first iteration, have it ignore the other rules (maybe like "if (i == 0) { //check to see if first char is part of the supplied word} else {//check conditions}) or something to that effect. Hope that helps.
Topic archived. No new replies allowed.