4.15. Converting Between Tabs and Spaces in a Text File
Problem
You have a text file that contains tabs or spaces, and you want to convert from one to the other. For example, you may want to replace all tabs with three spaces, or you may want to do just the opposite and replace occurrences of some number of spaces with a single tab.
Solution
Regardless of whether you are replacing tabs with spaces or spaces with tabs, use the
ifstream and ofstream classes in <fstream>. In
the first (simpler) case, read data in with an input stream, one character at a time,
examine it, and if it’s a tab, write some number of spaces to the output stream. Example 4-23 demonstrates how to do
this.
Example 4-23. Replacing tabs with spaces
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv) {
if (argc < 3)
return(EXIT_FAILURE);
ifstream in(argv[1]);
ofstream out(argv[2]);
if (!in || !out)
return(EXIT_FAILURE);
char c;
while (in.get(c)) {
if (c == '\t')
out << " "; // 3 spaces
else
out << c;
}
out.close();
if (out)
return(EXIT_SUCCESS);
else
return(EXIT_FAILURE);
}If, instead, you need to replace spaces with tabs, see Example 4-24. It contains the function
spacesToTabs that reads from an input stream, one character at a time, looking for three consecutive spaces. When it finds three in a row, it writes a tab to the output stream. For all other characters, or for fewer than three spaces, whatever is read from the input stream is written to the output ...