fork(1) download
  1. #include <fstream>
  2. #include <sstream>
  3. #include <iostream>
  4. #include <iomanip>
  5. #include <string>
  6.  
  7. void formatted_output(std::istream & in, std::ostream& out, std::size_t maxCharsPerLine)
  8. {
  9. bool done = false;
  10. unsigned charsInLine = 0;
  11.  
  12. std::string token;
  13. while ( in >> token )
  14. {
  15. std::size_t newLineSize = charsInLine + token.size();
  16. if (newLineSize <= maxCharsPerLine)
  17. {
  18. out << token;
  19. if (newLineSize == maxCharsPerLine || newLineSize+1 == maxCharsPerLine)
  20. {
  21. out << '\n';
  22. charsInLine = 0;
  23. }
  24. else
  25. {
  26. out << ' ';
  27. charsInLine += token.length() + 1;
  28. }
  29. }
  30. else
  31. {
  32. out << '\n';
  33. out << token << ' ';
  34. charsInLine = token.length() + 1;
  35. }
  36. }
  37.  
  38. out << '\n';
  39. }
  40.  
  41. const std::string content =
  42. "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor "
  43. "incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis "
  44. "nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. "
  45. "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu "
  46. "fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in "
  47. "culpa qui officia deserunt mollit anim id est laborum.";
  48.  
  49.  
  50. int main()
  51. {
  52. // std::ifstream in("input.txt");
  53.  
  54. // if ( !in.is_open() )
  55. // {
  56. // // ... error handling here.
  57. // }
  58.  
  59. std::istringstream in(content);
  60.  
  61. for (unsigned i = 1; i < 7; ++i)
  62. std::cout << std::setw(10) << i;
  63. std::cout << '\n';
  64.  
  65. std::cout << std::setfill('.');
  66. for (unsigned i = 1; i < 7; ++i)
  67. std::cout << std::setw(9) << "" << '0';
  68. std::cout << '\n';
  69.  
  70. formatted_output(in, std::cout, 60);
  71. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
         1         2         3         4         5         6
.........0.........0.........0.........0.........0.........0
Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
sed do eiusmod tempor incididunt ut labore et dolore magna 
aliqua. Ut enim ad minim veniam, quis nostrud exercitation 
ullamco laboris nisi ut aliquip ex ea commodo consequat. 
Duis aute irure dolor in reprehenderit in voluptate velit 
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia 
deserunt mollit anim id est laborum.