www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - [your code here]

reply "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
// Wraps long lines in standard input.
// Demonstrates D's powerful array manipulation facility and generic
// algorithms.

import std.algorithm;
import std.array;
import std.range;
import std.stdio;

void main() {
	int width = 80;

	foreach (line; stdin.byLine()) {
		while (line.length > width) {
			// Find longest space-terminated prefix of line that
			// fits in width, and wrap it there.
			char[] fits = find(retro(line[0..width]), " ").source;
			writeln(fits);
			line = line[fits.length .. $];
		}
		writeln(line);
	}
}
Apr 17 2012
parent reply "jerro" <a a.com> writes:
On Wednesday, 18 April 2012 at 01:59:19 UTC, H. S. Teoh wrote:
 // Wraps long lines in standard input.
 // Demonstrates D's powerful array manipulation facility and 
 generic
 // algorithms.

 import std.algorithm;
 import std.array;
 import std.range;
 import std.stdio;

 void main() {
 	int width = 80;

 	foreach (line; stdin.byLine()) {
 		while (line.length > width) {
 			// Find longest space-terminated prefix of line that
 			// fits in width, and wrap it there.
 			char[] fits = find(retro(line[0..width]), " ").source;
 			writeln(fits);
 			line = line[fits.length .. $];
 		}
 		writeln(line);
 	}
 }

There is a bug in this code. If a line is longer then width but doesn't contain spaces, find will return an empty range and the length of line will not decrease on each while loop iteration. So there is an endless loop.
Apr 17 2012
parent "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
On Wed, Apr 18, 2012 at 05:35:24AM +0200, jerro wrote:
[...]
 There is a bug in this code. If a line is longer then width but
 doesn't contain spaces, find will return an empty range and the
 length of line will not decrease on each while loop iteration. So
 there is an endless loop.

You're right, I forgot about that case. Here's the fixed code: ---------------------------------snip-------------------------------- // Wraps long lines in standard input. // Demonstrates D's powerful array manipulation facility and generic // algorithms. import std.algorithm; import std.array; import std.range; import std.stdio; void main() { int width = 80; foreach (line; stdin.byLine()) { while (line.length > width) { // Find longest space-terminated prefix of line that // fits in width, and wrap it there. char[] fits = find(retro(line[0..width]), " ").source; if (fits.length==0) fits = line[0 .. width]; writeln(fits); line = line[fits.length .. $]; } writeln(line); } } ---------------------------------snip-------------------------------- This code will forcefully truncate the line at width if no space is found. Thanks for finding the bug! T -- A mathematician is a device for turning coffee into theorems. -- P. Erdos
Apr 17 2012