fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <algorithm>
  5. #include <cctype>
  6. #include <sstream>
  7.  
  8. // invariant: line_sz > length of any single word
  9. std::vector<std::string> split( std::string str, std::size_t line_sz )
  10. {
  11. if( std::all_of( std::begin(str), std::end(str), [] ( char c ) { return std::isspace(c) ; } ) )
  12. return {} ; // empty string or string with all spaces, return an empty vector
  13.  
  14. std::vector<std::string> result(1) ; // vector containing one empty string
  15.  
  16. std::istringstream stm(str) ; // use a string stream to split on white-space
  17. std::string word ;
  18. while( stm >> word ) // for each word in the string
  19. {
  20. // if this word will fit into the current line, append the word to the current line
  21. if( ( result.back().size() + word.size() ) <= line_sz ) result.back() += word + ' ' ;
  22.  
  23. else
  24. {
  25. result.back().pop_back() ; // remove the trailing space at the end of the current line
  26. result.push_back( word + ' ' ) ; // and place this new word on the next line
  27. }
  28. }
  29.  
  30. result.back().pop_back() ; // remove the trailing space at the end of the last line
  31. return result ;
  32. }
  33.  
  34. int main()
  35. {
  36. const std::string str = "I need to write something that passes a value from! one program to another. "
  37. "This is a test (with a 20 character word) - ottffssentettffssent - end test." ;
  38.  
  39.  
  40. for( auto line : split( str, 25 ) ) std::cout << line << '\n' ;
  41. }
Success #stdin #stdout 0s 4464KB
stdin
Writing the rough draft is a transition, one that takes you from the mental aspect of note taking, outlining and prewriting to.
stdout
I need to write something
that passes a value from!
one program to another.
This is a test (with a 20
character word) -
ottffssentettffssent -
end test.