Squeeze Whitespace to Single Spaces in a Text File


You have a text file with whitespace of varying lengths in it, and you want to reduce every occurrence of a contiguous span of whitespace characters to a single space.


Use the operator>> function template, defined in , to read in continuous chunks of non-whitespace from a stream into a string. Then use its counterpart, operator<<, to write each of these chunks to an output stream, and append a single character after each one. Example 4-30 gives a short example of this technique.

Example 4-30. Squeezing whitespace to single spaces


using namespace std;

int main(int argc, char** argv) {

 if (argc < 3)

 ifstream in(argv[1]);
 ofstream out(argv[2]);

 if (!in || !out)

 string tmp;

 in >> tmp; // Grab the first word
 out << tmp; // Dump it to the output stream

 while (in >> tmp) { // operator>> ignores whitespace, so all I have
 out << ' '; // to do is add a space and each chunk of non-
 out << tmp; // whitespace

 out.close( );



This is a simple thing to do if you take advantage of streams and strings. Even if you have to implement a variation of thisfor example, you may want to preserve new linesthe same facilities do the trick. If you want to add new lines, you can use the solution presented in Recipe 4.16 to insert them in the right place.

See Also

Recipe 4.15 and Recipe 4.16

Building C++ Applications

Code Organization


Strings and Text

Dates and Times

Managing Data with Containers



Exceptions and Safety

Streams and Files

Science and Mathematics






show all menu

C++ Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2006
Pages: 241
Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net