fork(2) download
  1. #include <iostream>
  2.  
  3. std::string fmt(size_t margin, size_t width, std::string text)
  4. {
  5. std::string result;
  6. while (!text.empty())
  7. {
  8. result += std::string(margin, ' ');
  9. if (width >= text.size())
  10. return (result += text) += '\n';
  11. size_t n = width - 1;
  12. while (n > width / 2 && isalnum(text[n]) && isalnum(text[n - 1]))
  13. --n; // between characters - reduce width until word break or 1/2 width left
  14. (result += text.substr(0, n)) += '\n';
  15. text.erase(0, n);
  16. }
  17. return result;
  18. }
  19.  
  20. int main()
  21. {
  22. std::cout << fmt(5, 70,
  23. "This is essentially what I do with large blocks of "
  24. "descriptive text. It lets me see how long each of "
  25. "the lines will be, but it's really a hassle, see?");
  26.  
  27. }
Success #stdin #stdout 0s 3276KB
stdin
Standard input is empty
stdout
     This is essentially what I do with large blocks of descriptive text. 
     It lets me see how long each of the lines will be, but it's really a 
     hassle, see?