#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'.
。
发布于 2020-05-09 02:53:58
检查std::stack::pop
的签名:它返回void。您应该使用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
怎么办?
发布于 2020-05-09 03:11:48
而不是printf s.pop,使用printf s.top(),然后也使用pop s,将这个元素从堆栈中删除
https://stackoverflow.com/questions/61691137
复制相似问题