Previous Page

Output a user's string input in reverse - C++ console

Copy and Paste the following code into your favorite C++ Integrated Development Environment (IDE) - compile and run.

/*
    Output a string in reverse - By Brian Butler
*/

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

int main()
{
    string str;

    cout << "Enter a string: ";
    getline(cin, str); // get user's input for the string

    int size = str.size();  // get the size of the string
    char charArray[size];// new char array  size equal to the string size


/*======  Store your string in a character array  ======*/
     for (int i = 0; i < size; i++)
     {
         charArray[i] = str[i]; // The string "str" stored in the new
                                           // character array
     }



/*======  Output your character array in reverse =====*/
     for (int x = size - 1; x >= 0; x--)
     {
        cout << charArray[x];
     }


return 0;
}
//END OF CODE