The tricky part here is that a piece of advice ends when there are TWO newlines, meaning, one of the inputs is the empty string. For example, here are three pieces of advice:
1 2 3 4 5 6 7
|
An apple a day keeps the doctor away.
Time flies like an arrow.
Fruit flies like a banana.
A bird in the hand is worth two in the bush.
|
<-- blank line
<-- blank line
<-- notice the final blank line |
That blank line at the end of each piece of advice is important.
Use getline() until what you get is an empty line, that is, until
s.empty()
is true.
Next, you will want to be able to keep all those pieces of advice somewhere. Use a vector:
1 2
|
typedef std::vector <std::string> Advice;
typedef std::vector <Advice> List_of_Advice;
|
From there, write a function to read a single piece of advice into an Advice.
Then write a function to read a List_of_Advice, using the first function.
You should also write functions to write a single piece of advice (don’t forget the extra newline), and to write a list of advices.
From there, your program should open the “advice.txt” file, read all the pieces of advice. You should be able to reuse the functions, since a std::ifstream can be substituted for std::cin.
That is:
• Read the entire file. Write the last piece of advice to std::cout.
• Then use the first function to get a new piece of advice from std::cin.
Add it to the end of your list of advice.
• Finally, reopen the file (for rewrite, using
std::ofstream f( "advice.txt" );
) and write all the advices to the file.
Hope this helps.