相关疑难解决方法(0)

C中%n格式说明符的用途是什么?

%nC 中的格式说明符有什么用?有人可以用一个例子来解释吗?

c printf

116
推荐指数
7
解决办法
10万
查看次数

将零参数包传递给printf

我创建了一个具有可变参数模板方法的类.这个方法调用printf函数.将零参数传递给方法时,我得到gcc的编译警告说:

警告:格式不是字符串文字而没有格式参数[-Wformat-security]

一个简化的类示例是:

class printer{
    std::map<int,std::string> str;
  public:
    printer(){
      str[0] = "null\n";
      str[1] = "%4d\n";
      str[2] = "%4d %4d\n";
      str[3] = "%4d %4d\n%4d\n";
    }
    template<typename ...Args>
    void print(Args... args){
      printf(str[sizeof...(args)].c_str(),args...);
    }
};
Run Code Online (Sandbox Code Playgroud)

使用时

printer p;
p.print(23);
p.print(345,23);
Run Code Online (Sandbox Code Playgroud)

一切顺利,但使用时

printer p;
p.print();
Run Code Online (Sandbox Code Playgroud)

我收到编译警告

main.cpp: In instantiation of ‘void printer::print(Args ...) [with Args = {}]’:
main.cpp:23:11:   required from here
main.cpp:17:50: warning: format not a string literal and no format arguments [-Wformat-security]
       printf(str[sizeof...(args)].c_str(),args...);
Run Code Online (Sandbox Code Playgroud)

当然,如果我只是打电话

printf("null\n");
Run Code Online (Sandbox Code Playgroud)

没有警告出现.

有人可以解释为什么会这样吗?

我可以在不禁用-Wformat-security标志的情况下删除警告吗?

c++ gcc variadic

10
推荐指数
1
解决办法
682
查看次数

标签 统计

c ×1

c++ ×1

gcc ×1

printf ×1

variadic ×1