Search code examples
c++stringgetline

Find a word in a sentence c++


This code should say if a word is present in a sentence or not. When I insert the sentence and the word where I declare the strings(for exemple: string s = "the cat is on the table" string p = "table" the program says that the word is in the sentence) the code works but, with the getline, the for cycle never begin and it always says that the word isn't in the sentence.

Please help I dont know what to do

#include <iostream>
#include <string>

using namespace std;

int main () {

string s;

string p;

string word;

bool found = false;

int sl = s.length();

int beg = 0;

int pl = p.length();

cout << "sentence: ";

getline(cin, s);

cout << "word: ";

getline(cin, p);

for(int a = 0; a<sl; a++)
{
    if(s[a]== ' ')
{
    word = s.substr(beg, a-beg);
    if (word== p)
    {
      found = true;
      break;
    }
    beg = a+1;
    }
 }

 if (found== true)
 {
    cout <<"word " << p << " is in a sentence " << s;
 }

 else
{
 word = s.substr(beg);

 if (word== p)
    {
      found = true;
    }

if(found == true)
{
    cout <<"the word " << p << " is in the sentence " << s;
}

     else
   {
   cout <<"the word " << p << " isn't in the sentence " << s;
   }

  }
}

Solution

  • after taking the input strings then use length() to find the length, otherwise you are not taking the actual size of the strings.

    getline(cin, s);
    getline(cin, p);
    
    int sl = s.length();
    
    int pl = p.length();
    

    For splitting the words after taking the input string by getline() you can use stringstream which is a builtin c++ function, like :

    #include <sstream>
    #include <iostream>
    using namespace std;
    
    int main(){
        string arr;
        getline(cin, arr);
    
        stringstream ss(arr);
        string word;
         
        while(ss >> word){
           // your desired strings are in `word` one by one
           cout << word << "\n";
        }
    }
    

    Another thing is that you can declare the strings like string s, p, word;