-2

So I've been told to do a program in c++ where the user inputs a word and I have to instert it into an array, but the problem is when I have to invert the word:

#include <iostream>

using namespace std;

const int EOS = '.';
const int MAX = 30;

typedef char VectorC[MAX];

void showInversion (char word[MAX],int n)
{
    for (int i = n; i <= n-1 ; i--){
        cout << word[i];
    }
}
int main()
{
   VectorC word;
   char c = 'a';
   int i = 0, n = 0;

   cout << "ENTER SEQUENCE:" << endl;

   while (c!=EOS){
       word[i] = c = cin.get();
       i++;
       n++;   //length of the word
   }
   cout << "THE RESULT IS: " << showInversion(word,n);

   return 0;
}

Output example:

ENTER A SEQUENCE:

COMPUTER.

THE RESULT IS: RETUPMOC

magalenyo
  • 275
  • 6
  • 17
  • 1
    A simple google for "how to reverse a string c++" would give you more than enough information. – NathanOliver Dec 01 '15 at 15:34
  • What output are you getting? Offhand, I think you need to look at your for loop. You want to start at the last (non-null terminator) character (i.e. at index n-1) and decrement down until you output the first character (i.e. at index 0) – LiamT Dec 01 '15 at 15:35
  • _but the problem is when I have to invert the word_ --- it may help if you indicate what the problem actually is, rather than leaving it to your readers to speculate on. On a general reading of your code though, it seems that you would be well served to learn to use a debugger before running off to ask for help. Everyone needs help now and again but learning to solve your own problems, when practical, is essential and this does not seem to be a particularly difficult problem to solve. (Again, if you explained what the problem actually is, perhaps my view could be changed.) – mah Dec 01 '15 at 15:38
  • Thank you guys, I've found the answer already! I missunderstood how to treat the char array into the for, I mean, how to start from the last char to the first one. Thanks! – magalenyo Dec 01 '15 at 15:51

1 Answers1

0

To print inverted sequence, a simple way is to print the characters in word from the end to beginning.

void showInversion (char word[MAX],int n)
{
    for (int i = n - 1; i >= 0 ; i--){
        cout << word[i];
    }
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70