user4925
user4925

Reputation: 209

The last word in a string is not reversing

I am trying to reverse the words in a string.

Example, Input:as xsd bf would result in Output:sa dsx fb.

My problem is that the last word doesn't reverse.

Example,Input:as xsd bf would result in Output:sa dsx bf.As you can see bf doesn't get reversed.

My code,

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

void RevWords(string inp);


int main()
{
     string input;

     cout<<"Enter Sring:"<<endl;
     getline(cin,input);
     cout<<"Entered String:"<<input<<endl;
     RevWords(input);

     return 0;
}

void RevWords(string inp)
{
   int wordEnd=0,indexS=0,indexE=0;
   string newStr;
   newStr=inp;

   while(wordEnd<inp.length())
   {
       if(inp[wordEnd] != ' ')
      {
         wordEnd++;
      }
      else
      { 
         if(inp[wordEnd] == ' ' || inp[wordEnd] == '\0')
         {
             indexE=wordEnd-1;
             while(indexS<wordEnd)
             {
                newStr[indexS]=inp[indexE];
                indexS++;
                indexE--;
             }
             newStr[indexS]=' ';
             indexS++;
         }
         wordEnd++;
       }    
   }
   cout<<newStr<<endl;
}

Upvotes: 0

Views: 139

Answers (1)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

You don't handle the last word because you stop before you get there:

while(wordEnd<inp.length()) { // When you finally get to the last letter. You will 
                              // exit on the next loop iteration.
   if(inp[wordEnd] != ' ')

You need to change it to this:

 while(wordEnd<=inp.length()) {
   if(wordEnd < inp.length() && inp[wordEnd] != ' ') {
        //^ This is important so you dont go out of bounds on your string

Here is a live example.

Upvotes: 1

Related Questions