fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. void CStringSwitcher()
  6. {
  7. std::vector<std::string> inputs;
  8. size_t totalLength = 0;
  9.  
  10. std::cout << "Enter a sentence on each line. Input a 0 to stop." << std::endl;
  11. inputs.reserve(16);
  12.  
  13. for ( ; /* until break */ ; ) {
  14. std::cout << ">";
  15. std::string input;
  16. getline(std::cin, input);
  17. if (input == "0")
  18. break;
  19. inputs.push_back(input);
  20. totalLength += input.length() + 1; // for the '\n'
  21. }
  22.  
  23. std::string reversed = "";
  24. reversed.reserve(totalLength); // eliminate allocations
  25.  
  26. for (auto inputsIt = inputs.rbegin(); inputsIt != inputs.rend(); ++inputsIt) {
  27. const std::string& input = *(inputsIt);
  28.  
  29. #ifndef REAL_CODE
  30. // educational, Do-It-Yourself way
  31. const size_t length = input.length();
  32.  
  33. for (size_t i = 0; i < length; ++i) {
  34. reversed += input[length - 1 - i];
  35. }
  36. #else
  37. reversed.append(input.rbegin(), input.rend());
  38. #endif
  39.  
  40. reversed += '\n';
  41. }
  42.  
  43. std::cout << std::endl << reversed << std::endl;
  44.  
  45. // don't pause, set a break point at the end of the function
  46. // or run without debugging.
  47.  
  48. return;
  49. }
  50.  
  51. int main(int argc, const char* argv[])
  52. {
  53. CStringSwitcher();
  54.  
  55. return 0;
  56. }
  57.  
Success #stdin #stdout 0s 3480KB
stdin
Hello darkness, my old friend,
I've come to talk with you again,
Because a vision softly creeping,
And the vision that was planted in my brain
Still remains
Something something dark side
0

stdout
Enter a sentence on each line. Input a 0 to stop.
>>>>>>>
edis krad gnihtemos gnihtemoS
sniamer llitS
niarb ym ni detnalp saw taht noisiv eht dnA
,gnipeerc yltfos noisiv a esuaceB
,niaga uoy htiw klat ot emoc ev'I
,dneirf dlo ym ,ssenkrad olleH