finding in string

I want to find the position of str in str2 if it exists and say a number that shows where it starts. but my code won't give me a right answer if the sentence begins or ends with the word.(if the word is not found it should give -1)
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
29
30
31
32
33
34
35
36
  #include <iostream>       
#include <string>         
using namespace std;
int main ()
{ 
 int x;
  std::string str ;
   std::getline (std::cin,str);
  std::string str2 ;
   std::getline (std::cin,str2);
   x=str.find(str2);
   if(x)
{ std::string str3 ;
   str3=" "+str+ " ";
   std::string str4 ;
   str4=str+ " ";
   std::string str5 ;
   str5=" "+str;
   if (str3.find(str2)){
  	cout<<x+2;
}
    else if (str4.find(str2)){
   	cout<<x;
   }
   else if(str5.find(str2)){
   	cout<<x+2;
   }
   
}   
if (!x)
cout<<"-1";

  return 0;
}
   
}
Last edited on
I don't know what your code is trying to print, but find() return the position or npos for not found.
Topic archived. No new replies allowed.