C++ ostream Converting contents of a stream to upper case.

Description

C++ ostream Converting contents of a stream to upper case.

#include <iostream>
#include <fstream>
#include <cctype>
#include <string>
using std::string;

// Function to copy one stream to another converting to upper case
void copy(std::istream& in, std::ostream& out, char end = ' ')
{
  char ch {};//from  w  w  w. j a v a  2 s  . c o m

  while(in.get(ch))
  {
    if(end != ' ' && end == ch) // Check for end on cin
      break;
    out.put(std::toupper(ch));
  }
}

int main(int argc, char* argv[]) {
  string in {"s"};
  string out {"t"};
  std::cout << "Reading from " << in << " and writing to " << out << std::endl;

  bool kbd {in == "cin" || in == "std::cin"};         // Standard input stream indicator
  bool scrn {out == "cout" || out == "std::cout"};    // Standard output stream indicator
  char end {};                                        // Indicates end of input on cin;
  if (kbd)
  {
    std::cout << "\nEnter the character you want to indicate end of input: ";
    std::cin >> end;
    if(scrn)
      copy(std::cin, std::cout, end);
    else
    {
      std::ofstream outFile {out};
      if(!outFile)
      {
        std::cerr << "Failed to open output file. Program terminated.\n";
        exit(1);
      }
      copy(std::cin, outFile, end);
    }
  }
  else {
    std::ifstream inFile {in};
    if(!inFile)
    {
      std::cerr << "Failed to open input file. Program terminated.\n";
      exit(1);
    }
    if(scrn)
      copy(inFile, std::cout);
    else
    {
      std::ofstream outFile {out};
      if(!outFile)
      {
        std::cerr << "Failed to open output file. Program terminated.\n";
        exit(1);
      }
      copy(inFile, outFile);
    }
  }
  std::cout << "\n Stream copy complete." << std::endl;
}



PreviousNext

Related