Hi I am currently in an intro to c++ course and got this for an assignment. I know how to check if a number from a text file is even or odd but I don't know how to COUNT how many even and odd numbers are in the file.Please help.These are the directions:
Use the appropriate loop structure to process all of the numbers in the file, keeping track of the number of even values and the number of odd values. Additionally, output the actual number of even and odd values in the file.
You need to use some sort of loop to input the values in the file into an array (do you know how to do that?), and while you are doing it, you can have some kind of counter variable, say num_evens and num_odds, that are incremented whenever a number read from the file is even or odd, respectively.
You can read that document to understand how fstreams work. Once you understand that, it should be simple. You should input the values from a file into an array (you can use a loop for this), and in the same loop that you are inputting the values into the array, you can use the code you have written above and count the number of odds and evens.
I could have sworn I saw something about an array in there. Guess not.
OP, In any case, all that is really required is to output the number of evens and odds after counting them, which can be done in the aforementioned loop. You would still need to know how to use fstreams.
- Initialise your counts of evens and odds
- open your filestream (e.g. [code]ifstream input( "myfile.txt" );[/code] )
- loop whilst you can successfully read a num from file
{
- update count of even or odd according to num (as in your initial post)
}
- output your counts of even and odd