-
Word wrap
Hi, I'm writing a console application which requires quite large chunks of text to be displayed. When the text is output to the next line of the console individual words are broken up, is there an easy way of getting complete words to wrap onto the next line?
Thanks, Gareth.
-
Not that I know of. Unless you specfically define it, your console program won't be able to understand the difference between a half of a word and a whole word. The only thing you can do is format it according to the standard demensions of a console window.
For example, if the standard window is 80 characters wide, you have to stick an endl in your literal constant before it reaches that 80 characters. Even then, it won't look perfect if someone doesn't use standard windows or perhaps a different resolution.
Maybe someone knows an answer, but that's as far as I can get you.
-
You can write a function that accepts a string, a stream, and a column width that intelligently wraps words at the column width. Think of it as a filter between the processing and the output. The actual process isn't that complicated, you just find a span of characters that matches the column width, then walk back and add a newline at the first non-word character (such as whitespace).
-
Yeah, but do you know the function that returns the width of the screen?
-
>Yeah, but do you know the function that returns the width of the screen?
Yes, I do. :) But since it's not portable, that's why I said that the function takes a column width. Obviously the biggest issue for the OP is to get words to wrap without splitting.
-
Gareth,
Assuming you're writing a Windows console application, maybe you'll find something in the MSDN Console Reference.
I've done this in a Windows GUI program. There is a WinAPI function (which I can't remember right now) that, given a string and a font, returns the length in pixels. (Of course, there is another function that returns the Window-width in pixels.) There is probably an easier way to do it, assuming your console program uses a fixed-width font.
[EDIT] - Maybe the Windows console is always 80 columns??? I just opened-up a DOS / console program and I couldn't re-size it... (I'm not sure if this is a true-DOS program or a console program... and this computer doesn't have a compiler...)
-
isspace() is useful for this.