Q:

Write a program that takes the names of an input file and two output files

0

Write a program that takes the names of an input file and two output files. The input file should hold integers. Using an istream_iterator read the input file. Using ostream_iterators, write the odd numbers into the first output file. Each value should be followed by a space. Write the even numbers into the second file. Each of these values should be placed on a separate line.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <fstream>
#include <iostream>
#include <iterator>
#include <algorithm>


int main(int argc, char**argv) {
  if (argc < 4) {
    std::cerr << "Usage: 10.33 <input filename> <odd number output filename> "
                 "<even number output filename>" << std::endl;
    return -1;
  }
  std::ifstream in(argv[1]);
  if (!in.is_open()) {
    std::cerr << "Cannot open file: " << argv[1] << std::endl;
    return -2;
  }
  std::ofstream out_odd(argv[2]), out_even(argv[3]);
  if (!out_odd.is_open()) {
    std::cerr << "Cannot open file: " << argv[2] << std::endl;
    return -2;
  }
  if (!out_even.is_open()) {
    std::cerr << "Cannot open file: " << argv[3] << std::endl;
    return -2;
  }
  std::istream_iterator<int> i_iter(in), eof;
  std::ostream_iterator<int> odd_iter(out_odd, " "), even_iter(out_even, "\n");
  std::for_each(i_iter, eof,
      [&](int i) { i % 2 ? odd_iter = i : even_iter = i; });

  return 0;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now