-4

This assignment is called a co-currence problem. The point of my program is to read in sentences from a file and ignore any punctuation. Then, I will read user input where the user will enter words separated by a space only and I have to search for those exact words in all the sentences of the file and return the line number where all the words are found.

My approach now is to create a pointer array to other arrays that contain the words for each sentence.

ifstream read;
string filename; 
string **txtPtr = nullptr;
int numLines = 0;

getFileName();
getNumLines(read, fileName); //stores # of lines into numLines

txtPtr = new string*[numLines];

My question is, can I pass the pointer to a function as string *lines or string *lines[]?

ThrmsNPrfs
  • 35
  • 1
  • 5
  • You don't really have a clear question you're asking here. Splitting up each sentence into words makes a lot of sense. If you then have an array of arrays of words, you can loop through each one and check if one of the elements is equal to a word from user input. – Hoog Apr 12 '19 at 17:08
  • Thanks for the feedback. I've updated the code and my question. – ThrmsNPrfs Apr 12 '19 at 17:18
  • This question here: https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c covers splitting a string up in `c++` into substrings separated by a delimiter. Set your delimiter to `" "` and it will separate by word. – Hoog Apr 12 '19 at 17:21
  • I was thinking of breaking up the sentences as they are read in. Could I create an array of pointers that point to an array (one for each sentence) that contains the words? – ThrmsNPrfs Apr 12 '19 at 17:58
  • Yep, that's the way I would do it. With an array of pointers to arrays of your individual words per sentence you will be able to access each word with `wordsdArray[sentanceNumber][wordNumber]` which should make things easy for you to compare with the user inputs – Hoog Apr 12 '19 at 18:01

1 Answers1

0

I would parse the input file and build an index, and then I would look up user-entered words in that index. The index would be std::map with std::string as a key and with "Entry" struct as a value:

struct Entry {
    int line;
    int sentence;
};

typedef std::map<std::string, Entry> Index;

This is how insertion would look like:

Index index;

Entry val;
val.line = 1;
val.sentence = 2;

std::string word = "hi";
index.insert(Index::value_type(word, val));

This is how lookup would look like:

Index::iterator it = index.find(word);
if (it != index.end())
    std::cout << "found:" << it->second.line;

I know it's not the answer for your question, but it might help anyway..

Jiri Volejnik
  • 334
  • 1
  • 6