• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 181
  • Last Modified:

formatting text output

I want to output a string but i want to limit width of the column how do i do this?

string = "hello this is a test for width"

I want it to look like this:

cout  << string;

     hello this
     is a test
     for width

I know cout.width (5) will start 5 over but what will stop it at 15 plus i want it to wrap the word to the next line if the whole word won't fit on that line.
0
onestar
Asked:
onestar
1 Solution
 
Tommy HuiCommented:
You'll need to write the code yourself, i.e. manipulating the strings.

Start at the position you want to wrap at. Look at the character at that position. If it is a space, separate the original string into two substrings: the substring before that position and the substring after that position.

If it is not a space, then you'll need to look from that position to the beginning of the string, stopping at the first space. Once you have found a space, use the code from above to break up the string into two substrings.

If you do not find a space (i.e. reached the beginning of the string), then truncate at the desired position.

0
 
nietodCommented:
There is no built in feature for doing so, you will have to do it "manually" by counting the characters you output and wrapping as needed.

Do you need help implimenting that?
0
 
nietodCommented:
beat me by minute...
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
ozoCommented:
char *string = "hello this is a test for width";
char *s0 = string;
char *s1;
while( strlen(s0) > 10 && (s1 = strchr(s0,' ')) ){
        char *s2;
        while( (s2 = strchr(s1+1,' ')) && s2-s0 <= 10 ){ s1=s2; }
        *(s0 = s1) = '\n';
}

0
 
nietodCommented:
That's about half the length I would have come up with!
0
 
onestarAuthor Commented:
That works but I need it to start at certain amount of spaces over aswell.  I tried a few things but I could only get the first part over.

Ex.
     hello this
is a test
for width

Any suggestions?
0
 
onestarAuthor Commented:
How would I do this if I want to ask the user for the string?  When I tried this it would only put one word per line until the last line which it had two.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now