search for string within a string

Hi, in my current project there is an instance where i need to search a string of letters for another given string. both strings are declared as strings, and not char, and must be done this way. ive googled around and came across strstr(), but that only seems to work for string declared as char, unless i am mistaken. any advice on how i could go about doing this? heres a sample code showing what i want to do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
using namespace std;
int main ()
{
    string claimed;
    cin>>claimed;   //type in the word "bars"
    string possiblewords;
    possiblewords="abchdbarsljkd";
    string * pch;
  pch = strstr (possiblewords, claimed);  //this is what i tried earlier, but it did not work. i want to search possiblewords for the word bars. 
 if (claimed==pch)
        cout<<"claimed was found within possiblewords";
if (claimed !=pch)
        cout<<"claimed was not found within possiblewords";
  
  return 0;
}


thanks for any advice, i appreciate all the help i get here=]
Last edited on
Don't use cin>> with string objects; use getine(cin, claimed)

You can use the some functions already define by the string class:

http://www.cplusplus.com/reference/string/string/find/
http://www.cplusplus.com/reference/string/string/substr/
http://www.cplusplus.com/reference/string/string/c_str/
thanks for the reply=]
ive heard that in a few places, and just havent broken old habits. off curiosity, why shouldn't you use cin>> string?

thanks!
It reads only up to the next whitespace or newline, whichever comes first.
The user almost never expects their input to be truncated at whitespace; they expect it to end at the newline.

If you'd like to see specific examples of the problem search the forums for the keyword "getline" and read some of the threads. This is a very common problem that programmers run into and ask about.

Take a look at this example which explains yet another common problem with using cin instead of getline.
http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.6
totally makes sense now, ive actually noticed that but never put two and two together. thanks for the explanation=]
Topic archived. No new replies allowed.