Passing an integer to a formatted string in C

84 views Asked by At

I have found information only on conversion from int to string. However, is it possible to pass an integer to a formatted string in C?

The code I am trying to execute:

char a[] = {
    "%d"
};
a[0]= 0;
printf("%s", a);

However, the output is nothing. Have I screwed up in something or should I simply convert the value as the following seems to work:

char a[] = {
    "%s"
}
a[0] = "word";
printf("%s", a);
1

There are 1 answers

3
Mienislav On

Yes, it is possible. The approach is a bit different.

The most safe method is creating a fixed-size buffer like char buffer[100], then call the function from stdio.h called snprintf. This allows you to write into buffer any formatted string with any arguments you want.

This is a snippet how to do this in practice:

#include <stdio.h>

int main()
{
    int size = 100;
    char buffer[size]; // our buffer
    char pattern[] = "%d"; // formatted string; important remark: "%d" matches an integer.
    int num = 24; // the variable which we want to pass

    snprintf(buffer, size, pattern, num); // order of calling this function: a buffer, a size of the buffer, the formatted string, the remaining variables
    printf("%s\n", buffer);

    return 0;
}