Question
in c++ please, file I/O! write a main function that opens an input file text called nums.txt that contains integer values. (If you don't happen
in c++ please, file I/O!
write a main function that opens an input file text called "nums.txt" that contains integer values. (If you don't happen to have a "nums.txt" handy, you can easily create one with your text editor; just type some numbers on a dozen lines or so and save the file.) All your program has to do is read the values, one at a time, and if the value is even, write it to a file called "evens.txt", but if it's odd, write it to a file called "odds.txt". When all of the integers have been read and written, display a summary message that indicates how many even and odd numbers were copied.
But wait a minute -- how many integers should you read? As many as are in the "nums.txt" file! In other words, since you won't know ahead of time how many integer values are actually contained within "nums.txt" you'll have to test for successful extraction to see if you actually read an integer from the input file, and if you did, write it to the appropriate output file. Continue doing this until you fail to read an integer from the input file.
But how can you test for successful extraction? A simple way to do it is to use the extraction expression as a boolean expression. If the extraction fails, the entire extraction expression will evaluate to zero, so if that happens in the context of a boolean expression, zero is as good as false. So normally we see an extraction statement like this:
myFile >> myInt;
The problem with that code is that statement alone won't let you know if you actually succeeded in extracting an integer from the input file. But if you use the extraction code as a boolean expression, you'll know:
if (myFile >> myInt) { // the extraction was successful, myInt will contain the extracted value } else { // the extraction failed, myInt is left untouched }
It's important to note that when you use the extraction expression as a boolean expression, the extraction operator actually attempts to extract from the input stream, and if it succeeds, it will store the extracted value in the variable. But if the extraction fails, the variable won't be changed because nothing was extracted.
Of course, the skeletal code above is just a simple if/else statement, but for this assignment, you're going to have to loop. How will this information be useful in that situation? Hmm, something to ponder and think about...
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started