954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Reverse a char array (only words order) by pointers

I am a beginner & I need to implement this program which states that I have to reverse whatever is given in input via pointers...

For Example:
i) Input: This is reverse order program
Output: program order reverse is This

ii) Input: This is exercise eight
Output: eight exercise is This

I made it a little bit, but it outputs to "is input" if i input "The input is" string.

#include<iostream>
using namespace std;

int main()
{
    char sentence[80]={0};
    cout<<"Input the string: ";
    cin.getline(sentence,80,'\n');

    int length=strlen(sentence);
    int check=0;
    for(int i=length; i>0; i--)
    {
        if(sentence[i]!=' ')
        {
            check++;
        }
        else
        {
            for(int j=i; j<(check+i); j++)
                cout<<sentence[j+1];
            cout<<" ";
            check=0;
        }
    }
    return 0;
}


Thanks!

gamest
Newbie Poster
1 post since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

You are using the space as a deliminator, meaning you are breaking the words apart with a space. In the sentence "The input is" you get the space before is, then retrieve the word "is", you then get the space before input, and retrieve "is input" but there is no space before the word "The".

The letter 'T' of the word "The" resides in sentence[0]. Currently as written, line 12 will not execute when i = 0. You'll need to change that to

for(int i=length-1; i>=0; i--)

Your length value will be 12, so you will only need to reference sentence[11] through sentence[0]. Once you include the location sentence[0] in your for loop, you will need to check for that special condition, namly when i = 0. You can do that in your if statement in line 14. If i equals 0, then that is your first word of the sentence.

kes166
Practically a Master Poster
639 posts since Aug 2010
Reputation Points: 48
Solved Threads: 30
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: