0

The problem I'm having is that in the following loop, I'm attempting to read sentences one by one from the input file (inSentences) and output it into another file (outMatch), if it contains a certain word. I am not allowed to use any string functions except for .at() and .size().

The problem lies in that I'm trying to output the sentence first into a intermediary file and then use the extraction operator to get the word one by one to see if it has the word. If it does, it outputs the sentence into the outMatch file. While debugging I found that the sentence variable receives all of the sentences one by one, but the sentMore variable is always extracting out the first sentence of the file, so it's not able to test the rest of the sentences. I can't seem to fix this bug. Help would be greatly appreciated.

P.S. I don't really want the answer fleshed out, just a nudge or a clue in the right direction.

outMatch.open("match");
outTemp.open("temp");

while(getline(inSentences, sentence, '.')){

    outTemp << sentence;
    outTemp.close();
    inTemp.open("temp");

    while(inTemp >> sentMore){

        if(sentMore == word){

            cout << sentence << "." << endl;
            inTemp.close();
            sentCount++;
        }
    }
}
  • 1
    Instead of using an "intermediary file," use [string streams](https://stackoverflow.com/questions/20594520/what-exactly-does-stringstream-do) – scohe001 Oct 17 '17 at 15:48

1 Answers1

1

You should use string streams! Your issue right now appears to be that you never reopen outTemp, so after the first loop you're trying to write to it after you've closed it. But you can avoid all these problems by switching to stringstreams!

Since you don't want a full solution, an example may look like:

string line_of_text, word;
istringstream strm(line_of_text);
while(strm >> word) {
    cout << word << ' ';
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
scohe001
  • 15,110
  • 2
  • 31
  • 51
  • Is this a string function or in a different library? I'm not sure I can use this as per the guidelines for my project, not being allowed to use string functions except for .at and .size. – Karanveer Singh Oct 17 '17 at 16:30
  • @KaranveerSingh this is a whole library. Be sure to `#include ` – scohe001 Oct 17 '17 at 18:15