Removing surplus spaces from a stream. - C++ File Stream

C++ examples for File Stream:stream

Description

Removing surplus spaces from a stream.

Demo Code

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

void copy(std::istream& in, std::ostream& out, char end = ' ')
{
  char ch {};//from   w w  w  . j  a  v  a  2 s .c om
  bool gotSpace {false};        // True for first space in a sequence

  while(in.get(ch))
  {
    if(end != ' ' && end == ch) // Check for end on cin
      break;
    if(ch==' ')
      if(gotSpace)
        continue;
      else
        gotSpace= true;
    else
      gotSpace = false;
      out.put(ch);
  }
}

int main(int argc, char* argv[]){
  string in {"test"};
  string out {"target"};

  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 << "Enter 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;
}

Result


Related Tutorials