Last updated on July 27, 2020
Thesprintf() works just likeprintf() but instead of sending output to console it returns the formatted string.
Syntax:int sprintf(char *str, const char *control_string, [ arg_1, arg_2, ... ]);
The first argument tosprintf() function is a pointer to the target string. The rest of the arguments are the same as forprintf() function.
The function writes the data in the string pointed to bystr and returns the number of characters written tostr, excluding the null character. The return value is generally discarded. If an error occurs during the operation it returns-1.
The following program demonstrates how to usesprintf() function.
1 2 3 4 5 6 7 8 9101112131415161718192021222324252627 | #include<stdio.h>#include<string.h>intfactorial(int);intmain(){intsal;charname[30],designation[30],info[60];printf("Enter your name: ");gets(name);printf("Enter your designation: ");gets(designation);printf("Enter your salary: ");scanf("%d",&sal);sprintf(info,"Welcome %s !\nName: %s\nDesignation: %s\nSalary: %d",name,name,designation,sal);printf("\n%s",info);// signal to operating system program ran finereturn0;} |
Expected Output:
12345678 | Enter your name: BobEnter your designation: DeveloperEnter your salary: 230000Welcome Bob!Name: BobDesignation: DeveloperSalary: 230000 |
Another important use ofsprintf() function is to convert integer and float values to strings.
1 2 3 4 5 6 7 8 9101112131415161718192021 | #include<stdio.h>#include<string.h>intfactorial(int);intmain(){chars1[20];chars2[20];intx=100;floaty=300;sprintf(s1,"%d",x);sprintf(s2,"%f",y);printf("s1 = %s\n",s1);printf("s2 = %s\n",s2);// signal to operating system program ran finereturn0;} |
Expected Output:
12 | s1 = 100s2 = 300.000000 |