0

I code the program called "find the word" to detect a word in a paragraph then break it down. After it is done, then the word will be the next to break down to each character, then match it with the length of an array from each broke down word and paragraph. If it matches, it will printout the whole paragraph that matched the word that I insert. But, I can't insert the word that I'm trying to search. This is the code that I've typed :

#include <iostream>
#include <string>

using namespace std;

int x, y;

int main()
{
    string srctext = ""; 
    string word = "";
    string store = "";
    string character[10];
    int check = 0;
    int temp;

    cout << "Enter the Source Text: " << endl;
    cin >> srctext;

    cout << "Enter the Word to Find: " << endl;
    getline(cin, word);

    for(int i=0; i<srctext.length(); i++)
    {
        store = store + srctext[i];
        if(srctext[i] == '.' && srctext[i] == ' ' && i<srctext.length()-1)
        {
            character[check] = store;
            check++;
            store = "";
            store = i;
        }
    }

    int index = 0;
    bool isWord = false;
    bool prevChar = false;


    for(int i=0; i<srctext.length(); i++)
    {
        for(int j=0; j<word.length(); j++)
        {
            if(srctext[i] == word[j])
            {
                if(j == 0)
                {
                    index = i;
                    i++;

                    if(srctext[i] == word[word.length()-1])
                    {
                        isWord = true;

                        if(isWord == true)
                        {
                            cout << srctext[i];
                        }
                    }
                }
                else if(j != 0)
                {
                    if(prevChar == true)
                    {
                        if(srctext[i] == word[word.length()-1])
                        {
                            isWord = true;

                            if(isWord == true)
                            {
                                cout << srctext[i];
                            }
                        }
                    }
                }
            }
            else
            {
                i = index;
                break;
            }
            
        }
    }
}
  • `cin >> srctext;` - this reads only 1 word, not a whole text, and so `srctext[i] == ' '` will NEVER be true. Use `getline()` instead of `>>` to read in the text. `getline(cin, word);` - it makes more sense to use `>>` instead of `getline()` for reading the single word to search for. Also, `srctext[i] == '.' && srctext[i] == ' '` will NEVER be true, since a `char` can't be two different values at the same time. – Remy Lebeau Nov 06 '20 at 18:10

0 Answers0