【发布时间】:2013-08-06 16:03:21
【问题描述】:
我正在使用 Qt creator,它会产生这个错误:
“警告:格式 '%s' 需要 'char*' 类型的参数,
但参数 2 的类型为 'const void*' [-Wformat]"
控制台应用程序正在运行,但如果有办法避免此错误,我很感兴趣,只是感兴趣
#include <iostream>
#include <stdio.h>
using namespace std;
bool isOpen(FILE *file);
void print(const void *text);
#define FILE_IS_OPEN "The file is now open"
int main()
{
FILE *f;
f = fopen("This.txt", "w");
if(isOpen(f))
print(FILE_IS_OPEN);
fclose(f);
return 0;
}
bool isOpen(FILE *file) { return file != NULL ? true : false; }
void print(const void *text) { printf("%s\n", text); }
【问题讨论】:
-
为什么
print完全接受const void*参数? -
将签名改为
print(const char* test); -
错误信息很清楚。不过,如果你有可用的 C++,很多代码应该会真正改变。使用
std::fstream,这样您就不必自己关闭它。使用std::cout,这样您就不必担心匹配类型。使用std::string并更改FILE_IS_OPEN,因为宏绝对不是拥有常量字符串的最佳方式。摆脱isOpen并使用.is_open,并将print换成简单的std::cout <<。
标签: c++ string printf warnings c-preprocessor