#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;
}
我不明白为什么不能编译此行。
无法将'void'类型的表达式传递给可变参数函数;格式字符串的预期类型为'int'。
答案 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 然后也弹出,以将该元素从堆栈中取出