【问题标题】:error C2664: 'int printf(const char *const ,...)': cannot convert argument 2 from 'void' to '...'错误 C2664: 'int printf(const char *const ,...)': 无法将参数 2 从 'void' 转换为 '...'
【发布时间】:2020-05-09 02:45:20
【问题描述】:
#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”。

【问题讨论】:

  • pop() 不返回值,因此没有任何内容可打印。您想使用 s.top() 打印并使用 s.pop() 将顶部项目从堆栈中弹出。

标签: c++


【解决方案1】:

检查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 怎么办?

【讨论】:

    【解决方案2】:

    使用 printf s.top() 代替 printf s.pop 然后 pop 也一样,把这个元素出栈

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 2020-04-04
      相关资源
      最近更新 更多