简体   繁体   English

有没有办法在C中传递这样的字符串?

[英]Is there a way to pass strings like this in C?

I have a function which accepts a character array (ie, string) as argument. 我有一个接受字符数组(即字符串)作为参数的函数。

But an integer variable's value should also be printed as part of string. 但是,整数变量的值也应作为字符串的一部分打印。

For example, If I have a function like this: 例如,如果我有这样的功能:

int var=10;
void printStr(char str[])
{
   printf("%s", str);
}

and I need to print the value of integer variable 'var' with a message 我需要用消息打印整数变量“ var”的值

"The value of var is %d", var “ var的值为%d”,var

I tried this 我试过了

printStr( ("The value of var is %d", var) );

but it didn't work. 但这没用。

Is there a way to accomplish this without passing the variable as argument to printStr() ? 有没有一种方法可以在不将变量作为参数传递给printStr()

The output in this case should be 在这种情况下,输出应为

The value of var is 10 var的值是10

It seems that you need the function sprintf / snprintf for generation of the string. 似乎您需要函数sprintf / snprintf来生成字符串。

Try something like this: 尝试这样的事情:

char tempStr[30];
snprintf(tempStr, sizeof(tempStr), "The value of var is %d", var);
printStr(tempStr);

Is it what you need? 是你需要的吗?

Perhaps you might find variable number of arguments to functions and the GCC format attributes useful to building your thing. 也许您会发现函数的可变数量的参数GCC格式属性对于构建事物很有用。 You'll need to be using GCC for the attributes however, and not have any plans of being portable to other compilers. 但是,您将需要对属性使用GCC,并且没有任何可移植到其他编译器的计划。

I would not mess with these things however, and figure out a way to do things without this. 但是,我不会弄乱这些事情,并且想出了一种无需此操作的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM