Create another file called learner.cpp and copy the code in the image.
Let’s take a look at the respond function. The algorithm is fundamentally simple, but the file operations can be confusing.
On line 15 we create a file stream object and then assign the memory file on line 16. Notice the ios::in argument. This means that we want to open the file for input, i.e. to read the file.
At line 19 we begin a while loop which will continue until the end of file is reached.
Line 21, getline, will read a multi word line, where the cursor is currently sat, and then move to the next line for the future operation. The phrase is stored in the identifier variable.
On line 23 we see if the current phrase matches the user’s phrase. If it does we use getline again on line 25 to get the response underneath the matched phrase. The response is then said using the learner’s voice object, and then we leave the function on line 27.
If we reach the end of file and we have found no response, then we go to line 31, where we close the file.
On 32 we again open the file, but this time for output, i.e. program to file. We also add the ios::app argument to ensure that we append to the end of the file.
On 33 we write the initial phrase, and then repeat the phrase on 35 to prompt the user for an ideal response. The user’s response is then written, and the file is closed.
The say function on line 46 simply passes the phrase to the voice objects say function for textual and audible output.