【问题标题】:Printf and warning with #define stringPrintf 和带有#define 字符串的警告
【发布时间】: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 &lt;&lt;

标签: c++ string printf warnings c-preprocessor


【解决方案1】:

简单的改变

void print(const void *text);

void print(const char *text);

函数定义也是如此。

【讨论】:

    【解决方案2】:

    格式说明符%s 表示您正在尝试将字符串输出到控制台,因此它要求您在此处提供字符串的地址,该地址只不过是char *, 您可以将其转换为 (char *)text 并将其传递给 printf

    您也不能将void * 指针的内容输出到任何原始数据类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-22
      • 1970-01-01
      相关资源
      最近更新 更多