need help with reverse word program

Started by
1 comment, last by void* 19 years, 6 months ago
I'm trying to make a program that says hello backwards but you type it inthe regular way here's my code
#include<iostream>

using namespace std;
int main()
{
    int word = reverse();
    cout<<"hello\n";
    cin>>word;
    
    return 0;
}
-----------------------------------Panic and anxiety Disorder HQ
Advertisement
Hmmm.

Well you'll need to read the word in first. Also I suggest storing it as a string. Like this:

string teriyaki;

cin >> teriyaki;

Then you'll need to call your reverse function on it:

teriyaki = reverse(teriyaki);

cout << teriyaki; // print out the result


The reverse function itself should just re-order the bytes making up the string. To access the bytes in a string, the best thing to do is convert to an array of chars (chars are signed bytes):

string reverse(string in)
{
char* foo = in.c_str(); // .c_str() converts it to an array of chars
char bar[128]; // buffer to store it in

for (int i = 0; i < in.size(); ++i)
{
// loop through the string
char ch = foo;
bar[in.size() - i - 1] = ch; // put the char in reverse order
}

return string(bar);
}


Not sure if that will compile as I've just written it in a hurry, but it should work :)
---PS3dev
there's also a reverse iterator in the STL that works on string objects, if you intend to use a std::string.

But this question sounds awfully pedantic, so I'll let you look the details up instead of helping you with what might just be a homework question.
Greenspun's Tenth Rule of Programming: "Any sufficiently complicated C or Fortran program contains an ad-hoc, informally-specified bug-ridden slow implementation of half of Common Lisp."

This topic is closed to new replies.

Advertisement