Print string of user defined length

Hello all! I need help using strings in c++.

I have a long string that I need to print to an output file. The trick is that no lines are longer than some given length, inputted by the user. I must put as many words as possible on the same line. I can not break any words or put punctuation marks at the beginning of a new line.

Here is what I have been playing with to no avail:

allText is the long string that has other manipulations done already.
1
2
3
4
5
6
7
8
  int c = allText.size();
  for(int d = 0; d <= c; d++){
     for(int f = 0; f<=len;f++){
         outfile<<allText[f];
     }
     outfile<<endl;       
                
  }
closed account (o3hC5Di1)
Hi there,

The problem is in your second for-loop. Every time that ends, the first for loops starts a new iteration and f is set back to 0, meaning that it will again start at the beginning of the string.

One possible solution is to do the following:

1
2
3
4
5
6
7
8
9
10
11
  int c = allText.size();
  int f = 0;
  for(int d = 0; d <= c; d++){
  
     for(int i = 0; i<=len;i++){
         outfile<<allText[f];
         f++;
     }
     outfile<<endl;       
                
  }


Another possible solution is to use std::string::substr(): http://www.cplusplus.com/reference/string/string/substr/

1
2
3
4
5
6
7
int c = allText.size();
  int f = 0;
  for(int d = 0; d <= c; d++){
     outfile<<allText.substr(f, len);
     f += len;
     outfile<<endl;       
  }


Note that in order to determine whether there is whitespace or punctuation, you may want to have a look at the find-family of member functions: http://www.cplusplus.com/reference/string/string/substr/

Hope that gets you on your way, please do let us know if you have any further questions.

All the best,
NwN
Topic archived. No new replies allowed.