--Originally published at my programming blog
What I needed to do:
Write a function called find_bananas which receives a single parameter called filename (a string) and returns a positive integer which is the number of times the word (string) “banana” (or “BANANA” ) is found in the file. The banana can be any case (‘BaNana’ or ‘BANANA’ or ‘banana’, etc) and they can be “stuck together” like “banAnaBANANA” (that counts as two). Create your own test file (plain text) to check your work.
Thanks to this tutorial and this post.
So what I did was:
- I imported the library of fstream
- In the first function I did a for loop where if i is smaller than the length then with the function to lower the program will change all the letters to lower case.
- I also did an infinite loop (That’s why it has a 1 as a condition) this loop will only stop if you break it and in this I find the number of bananas of each line, and the program saves that info.
- Then at the end there is a break to end the infinite loop
- This function will return the number of bananas in each line
- Then in the next function I open the text file and read it and I made a counter that counts the accumulating bananas in each line of the text
- Finally in the int main I have a final counter and this will use the last functions and the return values will be returned.
My code in Github: https://gist.github.com/mariasantoyodl/31c998d729a8e608a0abfe31e59cf8e5