How to put a word in reverse/backwards?

Hey guys. Lets say I have my name "Kevin".

What would the program be so it reads "niveK"?

Can anyone write the program for that?
Last edited on
This is a great program for someone learning c++ so I don't think it'll do you much good to just have someone write it for you. Instead, i'll give you a couple of hints on how to do it (although there are many different ways).

Let's say we have the following string:
string reverse="reverse"

reverse[0] gives access to "r" and
reverse[6] or reverse[reverse.length] gives access to the last "e" in reverse

one could think of a way to make a loop that loops through the string in reverse and set each letter equal to the string as if it were running through the loop normally. Or vice versa.

so something kind of like

int j=0;
for(int i=string.length;i>0;i--){
//some code here

j++
}
Last edited on
This might be useful.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
#include<string>

using namespace std;

int main()
{
    int j=0;

    string word;
    string reverse_word;
    cin >> word;

    for (int i=word.size()-1; i>=0; i--) 
    {
        cout<<word[i];  
       
    }
   return 0;
}




Last edited on
@ jasongog: please use code tags when posting code.
http://www.cplusplus.com/articles/jEywvCM9/

@ bxrz: the program can be simplified by using std::reverse() or std::reverse_copy() from the algorithm library.

http://www.cplusplus.com/reference/algorithm/reverse/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <algorithm>
#include <iostream>
#include <string>

int main()
{
    std::string s;

    std::cout << "Enter string to be reversed: ";
    std::getline(std::cin, s);
    std::reverse(s.begin(), s.end());
    std::cout << "Resulting string is: \"" << s << "\".";
    std::cout << std::endl;
}


Or it can be simplified even more by using the "range constructor" of std::string:

template <class InputIterator>
  string  (InputIterator first, InputIterator last);

http://www.cplusplus.com/reference/string/string/string/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>

int main()
{
    std::string s;

    std::cout << "Enter string to be reversed: ";
    std::getline(std::cin, s);

    std::string rs(s.rbegin(), s.rend()); // Reversed String

    std::cout << "Resulting string is: \"" << rs << "\".";
    std::cout << std::endl;
}

Last edited on
Topic archived. No new replies allowed.