String Code that shows Reverse Order of what is Input

Write a program that accepts a strong of character from the user. The program should display the characters in reverse order. In other words, if the user enters the string "Programming", the program should display "gnimmargorP".


I don't even know were to begin with this code. Would appreciate any help I can get.
Update:

I have come up with this:

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;


int main() {
string input; // declare variable

cout << "Enter characters or word: ";
cin >> input; // get input from user

// output it in reverse order
for (int i = input.length(); i >= 0; --i) {
// output the char one by one according to character's index ( i-th letter in the word )
cout << input[i] ;
}
return 0;
}




I am missing an endl somewhere, I think. Because if I enter the word party the display shows as: ytrapPress any key to continue.....


What am I doing wrong?


Your code looks ok, just be aware that cin stops after the first whitespace so it might be better to use getline.
To have the wait message on a separate line put cout << "\n\n" before the return statement in main.
Where exactly would I use those? I have tried using both in different places but I'm not getting the correct result.
This line
 
    for (int i = input.length(); i >= 0; --i)
should be
 
    for (int i = input.length() - 1; i >= 0; --i)


Note the last character in the string is
 
    input[input.length() - 1]

without the -1, it is probably safe here, as it will likely access the null terminator. But it is an error which in other circumstances could give undefined behaviour- that is, it could cause incorrect results, program crash etc.
Last edited on
The iterator adapter std::ostream_iterator<char> allows using std::cout as a destination of algorithms (here std::copy) directly:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# include <iostream>
# include <string>
# include <algorithm>
# include <iterator>

int main()
{
    std::string input = "helloWorld";
    std::copy(input.crbegin(), input.crend(), std::ostream_iterator<char>(std::cout));
    std::cout << "\n";

   // reverse original string with spaces b/w characters:
    std::copy(input.crbegin(), input.crend(), std::ostream_iterator<char>(std::cout, " "));
}
Thanks so much!
Topic archived. No new replies allowed.