fork(8) download
  1. #include <iostream>
  2. #include <string>
  3. #include <cctype>
  4.  
  5. std::string word_wrap(std::string text, unsigned per_line)
  6. {
  7. unsigned line_begin = 0;
  8.  
  9. while (line_begin < text.size())
  10. {
  11. const unsigned ideal_end = line_begin + per_line ;
  12. unsigned line_end = ideal_end <= text.size() ? ideal_end : text.size()-1;
  13.  
  14. if (line_end == text.size() - 1)
  15. ++line_end;
  16. else if (std::isspace(text[line_end]))
  17. {
  18. text[line_end] = '\n';
  19. ++line_end;
  20. }
  21. else // backtrack
  22. {
  23. unsigned end = line_end;
  24. while ( end > line_begin && !std::isspace(text[end]))
  25. --end;
  26.  
  27. if (end != line_begin)
  28. {
  29. line_end = end;
  30. text[line_end++] = '\n';
  31. }
  32. else
  33. text.insert(line_end++, 1, '\n');
  34. }
  35.  
  36. line_begin = line_end;
  37. }
  38.  
  39. return text;
  40. }
  41.  
  42. int main()
  43. {
  44. std::string player_name = "Eric";
  45. std::string age = "152";
  46. std::string gender = "transgender";
  47.  
  48. enum body_type { fit, unfit };
  49. body_type body = fit;
  50.  
  51. std::string working_text = "Your name is " + player_name + " and you're " + age + " years old. You're a " + gender + " and your body type is ";
  52.  
  53. std::cout << word_wrap(working_text, 10) << "\n\n" ;
  54. std::cout << word_wrap(working_text + (body == fit ? "burly and strong." : "fat and blubbery."), 10) << '\n';
  55. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Your name
is Eric
and you're
152 years
old.
You're a
transgende
r and your
body type
is 

Your name
is Eric
and you're
152 years
old.
You're a
transgende
r and your
body type
is burly
and strong.