4

I am passing a string to my function, and the function is supposed to use that string to put individual chars in a stack. Then the stack is supposed to spit it back out (Since it's a stack it should be reversed). For example if my string is hello, it should print "olleh". But instead I'm getting ooooo. I think it has something to do with the fact that I'm setting ch equal to a different character every time but I'm not sure how to input those character in a different way.

void Stack::function2reverse(string myString) {

    int countItIt = 0;
    int sizeOfString = myString.size();
    char Ch ;
    for (int i= 0; i< sizeOfString; x++)
    {
        Ch = myString[x];
        stack.push(Ch);
        countIt ++;

    }

    while (countIt != 0)
    {    
        cout << Ch;
        stack.pop();
        countIt --;
    }
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
rose
  • 657
  • 2
  • 10
  • 20

1 Answers1

9

cout << Ch; - you print the same character every time (the last one entered, so 'o').

Instead, print the top character in the stack: std::cout << stack.top().

std::stack keeps track of its own size, so you don't need to worry about that either. Then you can replace your print loop with:

while (!stack.empty()) {
    std::cout << stack.top();
    stack.pop();
}

And of course, the Standard Library provides a std::reverse function anyway, so if this was not just an exercise in learning about std::stack, you could use that (and I can think of several other things to do as well, depending on exactly what you are trying to achieve):

std::string s = "hello";
std::reverse(std::begin(s), std::end(s));
// s now contains "olleh"

You may also want to read up on why using namespace std; is a bad practice.

Community
  • 1
  • 1
BoBTFish
  • 19,167
  • 3
  • 49
  • 76