Reversing a string with RULES!
My goal is to take a simple string like "My name is Don Knuth!", print it, then print it in reverse order. The rules are, I need to use this class
Code:
class ch_stack{
public:
void reset() {top = EMPTY; }
void push(char c) {top++; s[top] = c; }
char pop() {return s[top--]; }
char top_of() const {return s[top]; }
bool empty() const { return (top == EMPTY); }
bool full() const { return (top == FULL); }
private:
enum {max_len = 100, EMPTY = -1, FULL = max_len-1 };
char s[max_len];
int top;
};
And the function it comes out of can't actually print anything...it has to be a void function. So I have to send a string (let's call it s1) to this function, the function reverses the string into a new string (let's call it s2) and then int main simply prints s2 and there we should have it.
This is what I have
Code:
#include<iostream>
using namespace std;
//Function to modify a string and return its value in reverse order
void reverse(const char s1[], char s2[])
{
class ch_stack{
public:
void reset() {top = EMPTY; }
void push(char c) {top++; s[top] = c; }
char pop() {return s[top--]; }
char top_of() const {return s[top]; }
bool empty() const { return (top == EMPTY); }
bool full() const { return (top == FULL); }
private:
enum {max_len = 100, EMPTY = -1, FULL = max_len-1 };
char s[max_len];
int top;
};
ch_stack stack;
int i = 0;
while (s1[i] && !stack.full())
stack.push(s1[i++]);
while (!stack.empty())
s2[i] = stack.pop();
}
int main()
{
void reverse(const char s1[], char s2[]);
char s1[30] = { "My name is Don Knuth!" };
char s2[30]; //String to contain reverse values
cout << s1 << endl; //Show string's original value
reverse(s1, s2);
cout << s2 << endl; //Show string's final value
system("pause");
}
The two things I don't understand are how exactly to make a while loop, implementing that class, to reverse the string, and to have it all in a void function. How does int main know what s2 is if it's not part of its file scope? Does it have something to do with static or something like it? Any help would be great. I am a beginner, so please treat me like one.