Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

Create a C++ program that reads 100 numbers from the IN_Ask3.txt file and prints the…

  1. 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

  2. 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 fstream library without including iostream.

    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

    1. Includes: We include only the <fstream> header which is necessary for file handling.

    2. Namespace: The program uses the using namespace std; directive to avoid prefixing standard library names with std::.

    3. File Streams:

      • ifstream inputFile("IN_Ask3.txt"); is used to read from the input file.
      • ofstream evenFile("even.txt"); and ofstream oddFile("odd.txt"); are used to write to the even and odd number files respectively.
    4. Error Handling: The program checks if the input file opens successfully. If not, it returns 1 indicating an error.

    5. 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 to even.txt.
      • If the number is odd, it's written to odd.txt.
    6. 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.