Home > OS >  Is there possible ways to print a returning stack from a fuction?
Is there possible ways to print a returning stack from a fuction?

Time:03-16

I try to use stack function to convert decimal number to binary number and return the stack function value to main function but I am not able to output the correct result to the screen.(sorry for my English)

#include<iostream>
#include<stack>
using namespace std;
stack<int> BinaryNum(int k, stack<int> st){
    if(k >= 1){
        st.push(k % 2);
        return BinaryNum(k / 2, st);
    }
    if(k < 1)
        return st;
}
int main(){
    int k;
    cin >> k;
    stack<int> st;
    BinaryNum(k,st);
    while(!st.empty()){
        cout << st.top();
        st.pop();
    }
}

CodePudding user response:

You discard the result of BinaryNum in main, and are passing copies of your stack around.

Either use the result

int main(){
    int k;
    cin >> k;
    stack<int> st;
    st = BinaryNum(k,st);
    while(!st.empty()){
        cout << st.top();
        st.pop();
    }
}

or take st by reference in BinaryNum

stack<int> BinaryNum(int k, stack<int> & st){
    if(k >= 1){
        st.push(k % 2);
        return BinaryNum(k / 2, st);
    }
    if(k < 1)
        return st;
}

CodePudding user response:

You forgot to store the return value of your function in the variable st. Just change the line

BinaryNum(k,st);

to

st = BinaryNum(k,st);

and it will work.

  • Related