Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

4.16. Wrapping Lines in a Text File

Problem

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.

Solution

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);
}

Discussion

textWrap reads characters, one at ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page