0
#include <iostream>
#include <stack>

void convert(std::stack<char> &s, int n,int base)
{
    static char digit[]={
            '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
    };
    while(n>0)
    {
        s.push(digit[n%base]);
        n/=base;
    }
}

int main() {
    std::cout << "Hello, World!" << std::endl;
    std::stack<char> s;
    int n=89;
    int base=2;
    convert(s,n,base);
    while(!s.empty())
    {
        printf("%c",s.pop());//this line is can not be compiled.
    }
    return 0;
}

image

I do not understand why this line can not be compiled.

Cannot pass expression of type 'void' to variadic function;expected type from format string was 'int'.

1
  • 4
    pop() does not return a value so nothing to print. you want to use s.top() to print and s.pop() to pop the top item off the stack.
    – drescherjm
    May 9, 2020 at 2:49

2 Answers 2

2

Check the signature of std::stack::pop: it returns void. You should use top to get the value and pop to remove it.

The corrected code:

#include <iostream>
#include <stack>

void convert(std::stack<char> &s, int n,int base)
{
    static char digit[]={
            '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
    };
    while(n>0)
    {
        s.push(digit[n%base]);
        n/=base;
    }

}


int main() {
    std::cout << "Hello, World!" << std::endl;
    std::stack<char> s;
    int n=89;
    int base=2;
    convert(s,n,base);
    while(!s.empty())
    {
        printf("%c",s.top());
        s.pop();
    }
    return 0;
}

General comment on your code: what if you provide a negative n to the function?

0

Instead of printf s.pop use printf s.top() Then pop s as well, to take this element out of stack

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.