Replacing spaces with tabs in a file - C++ File Stream

C++ examples for File Stream:Text File

Description

Replacing spaces with tabs in a file

Demo Code

#include <iostream>
#include <istream>
#include <ostream>
#include <fstream>
#include <cstdlib>

using namespace std;

void spacesToTabs(istream& in, ostream& out, int spaceLimit) {

   int consecSpaces = 0;

   char c;/*w ww .  ja v a 2s  .c om*/

   while (in.get(c)) {
      if (c != ' ') {
         if (consecSpaces > 0) {
            for (int i = 0; i < consecSpaces; i++) {
               out.put(' ');
            }
            consecSpaces = 0;
         }
         out.put(c);
      } else {
         if (++consecSpaces == spaceLimit) {
            out.put('\t');
            consecSpaces = 0;
         }
      }
   }
}

int main(int argc, char** argv) {
   ifstream in("main.cpp");
   ofstream out("target.txt");

   if (!in || !out)
      return(EXIT_FAILURE);

   spacesToTabs(in, out, 3);

   out.close();

   if (out)
      return(EXIT_SUCCESS);
   else
      return(EXIT_FAILURE);
}

Related Tutorials