to find a word in a string

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 <stdio.h>
#include <iomanip>
#include<string>
using namespace std;
int main()
{
string s;
getline(cin,s);
cout<<s<<endl;
int c=0,f=0,r=0;
for(int i=0;i<s.size();i++)
{
if(s[i]==' ')
c++;
if(s[i]==' ' && c==2)
f=i;
if(s[i]==' ' && c==3)
r=i;
}
cout<<c<<endl;
for(int j=f+1;j<=r; j++)
{cout<<s[j];}
cout<<endl;
return 0;}

but it is giving me in the output:
1
2
3
i like c++
i like c++
2

so it's not giving me the third word! can anyone help me?
Last edited on
When the program reaches the last for-loop, r is still zero. Can you see why?

As a hint, try the typing i like c++ with one extra space after c++ and another time with one extra space before i.
thanks :) now it's giving me the third word
Topic archived. No new replies allowed.