Create a C++ program that reads 100 numbers from the IN_Ask3.txt file and prints the…
- User
Create a C++ program that reads 100 numbers from the IN_Ask3.txt file and prints the even numbers in the even.txt file and the odd ones in the odd.txt file. use namespace std and fstream without iostream
- Assistant
Here is an example of a C++ program that reads 100 numbers from a file named IN_Ask3.txt and then writes the even numbers to even.txt and the odd numbers to odd.txt. It uses the
fstreamlibrary without includingiostream.C++ Program
#include <fstream> using namespace std; int main() { // Input and Output file streams ifstream inputFile("IN_Ask3.txt"); ofstream evenFile("even.txt"); ofstream oddFile("odd.txt"); // Check if the input file is open if (!inputFile) { return 1; // Exit if the file cannot be opened } int number; int count = 0; // Count the numbers read // Read numbers from the file while (inputFile >> number && count < 100) { // Check if the number is even or odd if (number % 2 == 0) { evenFile << number << endl; // Write to even.txt } else { oddFile << number << endl; // Write to odd.txt } count++; // Increment the count } // Close the files inputFile.close(); evenFile.close(); oddFile.close(); return 0; // Exit the program }Explanation
-
Includes: We include only the
<fstream>header which is necessary for file handling. -
Namespace: The program uses the
using namespace std;directive to avoid prefixing standard library names withstd::. -
File Streams:
ifstream inputFile("IN_Ask3.txt");is used to read from the input file.ofstream evenFile("even.txt");andofstream oddFile("odd.txt");are used to write to the even and odd number files respectively.
-
Error Handling: The program checks if the input file opens successfully. If not, it returns
1indicating an error. -
Reading Numbers: A loop reads up to 100 integers from the input file. For each number:
- If the number is even (
number % 2 == 0), it's written toeven.txt. - If the number is odd, it's written to
odd.txt.
- If the number is even (
-
Closing Files: Finally, all opened files are closed properly.
Note
Ensure that the input file IN_Ask3.txt exists in the same directory as your compiled program, and it contains at least 100 integers for the program to function correctly. Each integer should be separated by whitespace.
-