c++ - 在 printf 中使用#define?

标签 c++ string c-preprocessor

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

我有这个:

#define _APPID_ "Hello World!"

然后是简单的 printf,将其调用到 %s(字符串)中。它把这个放出来了:

simple.cpp:32: 错误:无法将参数“1”的“_IO_FILE*”转换为“const char*”到“int printf(const char*, ...)”

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

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

但它没有用,我认为是同样的错误。

最佳答案

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

#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_)(尽管它应该仍然有效)。

关于c++ - 在 printf 中使用#define?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3011220/

相关文章:

c# - 使用 C# 格式化字符串中的句子

c - scanf()读取自己的输入和后面scanf()的输入

gcc - 自定义 gcc 预处理器

c++ - 为特定文件定义

c++ - 从整数转换为指针

c++ - 错误 C2143 : syntax error : missing ',' before '<'

c++ - 使用 C++ 的 std::move 从内部范围内的对象到外部范围安全吗?

c++ - 我们如何让一个共享指针指向另一个共享指针的对象呢?

c++ - 没有虚拟析构函数的继承

C - fgets() - 如果字符串更长怎么办?