J...S J...S - 2 months ago 5
C Question

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


"The value of var is %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()
?

The output in this case should be


The value of var is 10

Answer

It seems that you need the function sprintf/snprintf for generation of the string.

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?