#include<iostream>
using namespace std;
int main()
{
int word = reverse();
cout<<"hello\n";
cin>>word;
return 0;
}
need help with reverse word program
I'm trying to make a program that says hello backwards but you type it inthe regular way here's my code
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 :)
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 :)
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement