c str add int
To add an integer to a C string, you can use the sprintf
function. Here's an example:
#include <stdio.h>
int main() {
char str[100];
int num = 42;
sprintf(str, "The number is %d", num);
printf("%s\n", str);
return 0;
}
In this example, we declare a character array str
with a size of 100 to hold the resulting string. We also declare an integer variable num
and initialize it with the value 42.
The sprintf
function takes a format string and additional arguments, and it formats them into a string, which is then stored in the str
array. In this case, we use the format string "The number is %d"
to specify that we want to include the integer value in the string. The %d
is a placeholder that will be replaced with the value of num
when the string is formatted.
After calling sprintf
, the resulting string is stored in str
. We can then print the string using printf
and the %s
format specifier.
When you run this program, the output will be:
The number is 42
This demonstrates how to add an integer to a C string using the sprintf
function.