Trusted answers to developer questions

How to use the sprintf() method in C

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Using the library function sprintf() is the easiest way to convert an integer to a string in C.

svg viewer

Syntax

The function is declared in C as:

int sprintf(char *str, const char *format, [arg1, arg2, ... ]);

where,

  • str is a character array on which data is written.
  • format is a C string which describes the output, along with placeholders for the integer arguments to be inserted in the formatted string. It follows the same specifications as printf().
  • [arg1,arg2...] are the integer(s) to be converted.

Note the function’s return type is int - it returns the length of the converted string.

The following examples will make it clearer:

Examples

int main() {
float num = 9.34;
printf("I'm a float, look: %f\n", num);
char output[50]; //for storing the converted string
sprintf(output, "%f", num);
printf("Look, I'm now a string: %s", output);
}

1. Multiple arguments can also be used:

int main() {
char output[50];
int num1 = 3, num2 = 5, ans;
ans = num1 * num2;
sprintf(output, "%d multiplied by %d is %d", num1, num2, ans);
printf("%s", output);
return 0;
}

2. sprintf returns the length of the converted string, as shown below:

int main() {
int num = 3003;
int length;
char output[50]; //for storing the converted string
length = sprintf(output, "%d", num);
printf("The converted string is %s and its length is %d.", output, length);
}

RELATED TAGS

integer
string
conversion
c
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?