【问题标题】:Use a #define in printf?在 printf 中使用#define?
【发布时间】:2011-03-01 23:20:30
【问题描述】:

我想为应用程序 ID 使用某种常量(这样我就可以在 printf 中使用它)。

我有这个:

#define _APPID_ "Hello World!"

然后是简单的 printf,将其调用为 %s(字符串)。它把它说出来:

simple.cpp:32: error: cannot convert ‘_IO_FILE*’ to ‘const char*’ for argument ‘1’ to ‘int printf(const char*, ...)’

我将使用什么来定义要在 printf 中使用的应用程序 ID?我试过了:

static const char _APPID_[] = "Hello World"`

但它不起作用,我认为同样的错误。

【问题讨论】:

  • 能否请您发布实际的 printf() 行?还要指出你正在使用什么编译器。
  • 同样的错误“你认为”?它要么是,要么不是。你编译了代码,而不是我们。如果您不知道自己遇到了什么错误,您希望其他人如何?
  • #defineprintf() ?你确定这是一个 C++ 问题吗?

标签: c++ string c-preprocessor


【解决方案1】:

我不确定我是否完全理解你的尝试......但这有效:

#include <stdio.h>

#define _APPID_ "Hello world"

int main()
{
    printf("The app id is " _APPID_ "\n");
    /* Output: The app id is Hello world */
    return 0;
}

当出现两个背靠背的常量字符串(即"hello " "world")时,编译器会将它们视为单个连接的常量字符串("hello world")。

这意味着在尝试printf 编译时常量字符串的情况下,您不需要使用printf("%s", _APPID_)(尽管这应该仍然有效)。

【讨论】:

  • 实际上,请使用printf("%s", APP_ID)。如果您曾经将您的应用程序重命名为“200% 生产力助推器”,那么调用 printf(APP_ID) 就不太好用了。
  • 如果您使用 PRIuPTR 或 inttypes.h 中的其他格式化程序, printf("text " PRIuPTR "more text", 4);是唯一的出路。 stackoverflow.com/questions/1403074/…
【解决方案2】:

根据报错信息,问题很可能不是字符串常量引起的,而是给printf()的参数不正确。

如果你想打印到一个文件,你应该使用fprintf(),而不是printf()。如果要打印到屏幕上,请使用printf(),但不要将文件句柄作为其第一个参数。

【讨论】:

    【解决方案3】:

    在 source.h 中

    #ifndef _SOURCE_H
    #define SOURCE_H
    #ifdef APP_ID
    #define WHOAMI printf("%s\n", APP_ID);
    #endif
    #endif
    

    在你的程序中:

    #define APP_ID __FILE__
    #include "source.h"
    int main()
    {
        WHOAMI
        return 0;
    }
    

    这样做的原因是有一个标准的包含文件 - source.h。头文件中的__FILE__返回头文件的名称,因此APP_ID定义被限制在C文件中。

    如果不定义 APP_ID,代码将无法编译。

    【讨论】:

      【解决方案4】:

      _APPID_ 是为实现保留的名称。它匹配模式^_[A-Z].*

      将其重命名为例如APP_ID

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-06
        • 2012-01-29
        • 1970-01-01
        相关资源
        最近更新 更多