错误C2664:'int printf(const char * const,...)':无法将参数2从'void'转换为'...'

时间:2020-05-09 02:45:20

标签: c++

#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

我不明白为什么不能编译此行。

无法将'void'类型的表达式传递给可变参数函数;格式字符串的预期类型为'int'。

2 个答案:

答案 0 :(得分:2)

检查std::stack::pop的签名:它返回空。您应该使用top来获取值,并使用pop来删除它。

更正的代码:

#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;
}

对代码的一般评论:如果为函数提供否定的n,该怎么办?

答案 1 :(得分:0)

使用printf s.top()代替printf s.pop 然后也弹出,以将该元素从堆栈中取出

相关问题