-3

Hey guys I'm new here and a programming noob so bear with me here.

This is for my C++ class which sadly my teacher is terrible at teaching so many things confuse me so I need some help here.

We have a lab that is called 'Reverse Sentence' and this is what it wants In this lab.

Write the function "ReverseSentence" that takes a string parameter and changes it, by reversing it.

For example:

INPUT: the first test

OUTPUT: tset tsrif eht

The function must not use an extra string, but must reverse the elements of the input string.

#include <iostream>
#include <string>
using namespace std;

void ReverseSentence( string& inputSentence){

   /* Body of Function Here */

}

int main(){
   string inputSentence;
   cout << "Input your sentence: ";
   getline(cin, inputSentence);
   cout << endl;

   ReverseSentence(inputSentence);
   cout << "Reversed Sentence:" << endl;
   cout << inputSentence << endl;

   return 0;
}

Can someone please help me what function is because I'm having trouble with it.

Community
  • 1
  • 1
Hecx
  • 1
  • In shortly: half of the cycle(length/2) and swap. – Isabek Tashiev Nov 15 '15 at 09:47
  • I assume that you are supposed to implement the code yourself, and not use e.g. `std::reverse`? Then, how do you access the last character of a string? The second to last? And so on. Maybe there's some nice iterators to handle it, have you checked [a `std::string` reference](http://en.cppreference.com/w/cpp/string/basic_string)? – Some programmer dude Nov 15 '15 at 09:48

2 Answers2

1

Just use std::reverse:

void ReverseSentence( string& inputSentence){
  std::reverse(inputSentence.begin(), inputSentence.end());
}
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
1

Half of the cycle and swap.

#include<algorithm>
#include<string>

void ReverseSentence(std::string &s){
   for (int i = 0; i < s.size()/2; ++i)
      std::swap(s[i], s[s.size() - i - 1]);
}
Isabek Tashiev
  • 1,036
  • 1
  • 8
  • 14