C语言 在 printf 语句中连接字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14035769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:51:24  来源:igfitidea点击:

concatenating strings in a printf statement

cprintf

提问by ant2009

gcc 4.7.2
c89

Hello,

你好,

#define LOG_ERR(fmt, ...)                                               \
    fprintf(stderr, "[ERROR] %s:%d: error [%s] " fmt "\n", __func__, __LINE__, strerror(errno), ##__VA_ARGS__)

And I am using it like this:

我是这样使用它的:

LOG_ERR("Failed to connect to message queue [ %d ]", msg_id);

The fmt has been concatenated in the fprintf statement. How is this possible?

fmt 已连接在 fprintf 语句中。这怎么可能?

I have tried to do the same with the following below just to test the concept, but failed with a compile error:

我试图用下面的方法做同样的事情来测试这个概念,但由于编译错误而失败:

/* Using char array */
const char name[] = "Joe";

printf("Hello how " name " how are you today?\n");

Using constant string literal
const char *name = "Joe";

printf("Hello how " name " how are you today?\n");

Both game me the following error:

两个游戏都出现以下错误:

expected ')' before name

Many thanks for any suggestions,

非常感谢您的任何建议,

回答by Mike

You need a format specifier, check out the documentation for printf

您需要一个格式说明符,请查看printf文档

const char *name = "Joe"; // or your char array, either's fine

printf("Hello how %s how are you today?\n", name);

Your attempt:

你的尝试:

printf("Hello how " name " how are you today?\n");

Looks a little more C++ish

看起来更像 C++ish

cout << "Hello how " << name << "are you today?\n";

回答by pyrospade

Difference is that the macro is textually replacing the word fmtwith your string. Putting two or more literal strings together gets you the concatenation of those strings.

不同之处在于宏正在fmt用您的字符串文本替换单词。将两个或多个文字字符串放在一起可以获得这些字符串的串联。

"Hello " "World" "!!"
/* is the same as */
"Hello World!!"

Remember, only literalstrings will do this. This does notwork for variables.

请记住,只有文字字符串才能做到这一点。这不适用于变量。

Think of macros like a find/replace in your code. To illustrate, consider your macro definition -

将宏视为代码中的查找/替换。为了说明,请考虑您的宏定义 -

#define LOG_ERR(fmt, ...)  \
    fprintf(stderr, "[ERROR] %s:%d: error [%s] " fmt "\n",
            __func__, __LINE__, strerror(errno), ##__VA_ARGS__)

When you use it like this -

当你像这样使用它时——

LOG_ERR("Failed to connect to message queue [ %d ]", msg_id);

It does a textual replacement and becomes -

它进行文本替换并变成 -

fprintf(stderr, "[ERROR] %s:%d: error [%s] " "Failed to connect to message queue [ %d ]" "\n",
            __func__, __LINE__, strerror(errno), msg_id)

The side-by-side strings and concatenated and voila -

并排的字符串和连接和瞧 -

fprintf(stderr, "[ERROR] %s:%d: error [%s] Failed to connect to message queue [ %d ]\n",
            __func__, __LINE__, strerror(errno), msg_id)

回答by Andrew Frost

When it fails, it's because you're using variables. String literals can be concatenated by the compiler i.e. if you write "abc" "123" then the compiler will treat this as "abc123". And when you do this in the macro, the preprocessor means that this is exactly what is sent to the compiler

当它失败时,那是因为您使用了变量。字符串文字可以由编译器连接,即如果你写“abc”“123”,那么编译器会将其视为“abc123”。当您在宏中执行此操作时,预处理器意味着这正是发送给编译器的内容

LOG_ERR("Failed to connect to message queue [ %d ]", msg_id);

becomes

变成

fprintf(stderr, "[ERROR] %s:%d: error [%s] " "Failed to connect to message queue [ %d ]" "\n", myfunction, 123, strerror(errno), msg_id);

Might be worth checking out the stringizer and concatenation macros too (for the preprocessor - #and ##and I never remember which is which...)

Andrew

可能是值得一试的stringizer和连接宏太(用于预处理-#而且##,我从来没有记住哪个是哪个?)

安德鲁

回答by NeonGlow

If you want to define a macro for fprintf()you may do like this which is simplest IMHO.

如果你想为fprintf()你定义一个宏,你可以这样做,这是最简单的恕我直言。

#define LOG_ERR(...)   fprintf(stderr, __VA_ARGS__)

and use it like

并像使用它一样

int main()
{

    int  myVar =100;

    LOG_ERR ("The value of myVar is %d", myVar); 

    return 0; 
}

回答by zhen liu

#include <stdio.h>
#include <sys/time.h>
#include <string>

#define MyPrint(...) {\
struct timeval tv;\
gettimeofday(&tv,0);\
printf("%d.%d:", (unsigned int)tv.tv_sec, (unsigned int)tv.tv_usec);\
printf(__VA_ARGS__);}