I am currently trying to make a function that can read a phrase, that consist of combining 2 to 3 adjacent words, from a text file. At the moment my function does that but it eventually concatenates to form the whole article instead of just 2 to 3 words per phrase.
This is my current code:
int Dictionary::processFilePhrases(string file) {
vector<string> wordList;
string word;
string phrase;
ifstream fin;
fin.open(file.c_str());
while (fin >> word) {
wordList.push_back(word);
}
fin.close();
for (int i=0; i<wordList.size(); i++){
phrase += wordList[i] + " ";
cout << phrase << endl;
}
return wordCount;
}
for example:
input file text: “The next frontier for game-playing artificial intelligence”
The goal is to output words so its like:
the
the next
the next frontier
next
next frontier
next frontier for
frontier
frontier for
frontier for game-playing
…
etc.
2
Answers
Well the “concatenating” loop runs once over all the words you got, so that’s why you get all the words.
The way you describe the wanted output, it seems like you want two loops, nested inside each other, where the inner loops from one to n, and where n is the current value from the outer loop.
Perhaps something like
If we now step through the code above, in the first iteration of the outer loop,
i
is equal to zero. In the inner loop we loop whilej
is less than or equal toi
(which now is zero), which means the inner loop will iterate only once, makingphrase
equal to the string"The "
(with the input you have given in the question).Once the inner loop finishes the phrase is printed, and the outer loop iterates, which makes
i
equal to one. The inner loop now iterates two times (forj
being zero and one) constructing the phrase"The next "
.Of course this doesn’t exactly do what you want, printing only up to three words at a time, and starting with the next word after the three first words have been printed. You probably need yet another loop, to handle the one to three counting. The above is a starting point though, and I suggest you experiment with that, and other loops outside the outer, in between, and as a new inner loop. Experimentation and failure is how you learn.
Something like this(I didn’t run it):