November 2005
Beginner to intermediate
594 pages
16h 23m
English
You want to “wrap” text at a specific number of characters in a file. For example, if you want to wrap text at 72 characters, you would insert a new-line character after every 72 characters in the file. If the file contains human-readable text, you probably want to avoid splitting words.
Write a function that uses input and output streams to read in characters with
istream::get(char), do some bookkeeping, and write
out characters with ostream::put(char). Example 4-25 shows how to do this for text
files that contain human-readable text without splitting words.
Example 4-25. Wrapping text
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cctype>
#include <functional>
using namespace std;
void textWrap(istream& in, ostream& out, size_t width) {
string tmp;
char cur = '\0';
char last = '\0';
size_t i = 0;
while (in.get(cur)) {
if (++i == width) {
ltrimws(tmp); // ltrim as in Recipe
out << '\n' << tmp; // 4.1
i = tmp.length();
tmp.clear();
} else if (isspace(cur) && // This is the end of
!isspace(last)) { // a word
out << tmp;
tmp.clear();
}
tmp += cur;
last = cur;
}
}
int main(int argc, char** argv) {
if (argc < 3)
return(EXIT_FAILURE);
int w = 72;
ifstream in(argv[1]);
ofstream out(argv[2]);
if (!in || !out)
return(EXIT_FAILURE);
if (argc == 4)
w = atoi(argv[3]);
textWrap(in, out, w);
out.close();
if (out)
return(EXIT_SUCCESS);
else
return(EXIT_FAILURE);
}textWrap reads characters, one at ...