Sunday, September 22, 2024
Google search engine

sprintf() in C

Syntax: 

int sprintf(char *str, const char *string,...); 

Return: 

If successful,
it returns the total number of 
characters written excluding 
null-character appended in the string, 
in case of failure a negative number 
is returned .

sprintf stands for “String print”. Instead of printing on console, it store output on char buffer which are specified in sprintf.

C




// Example program to demonstrate sprintf()
#include <stdio.h>
int main()
{
    char buffer[50];
    int a = 10, b = 20, c;
    c = a + b;
    sprintf(buffer, "Sum of %d and %d is %d", a, b, c);
 
    // The string "sum of 10 and 20 is 30" is stored
    // into buffer instead of printing on stdout
    printf("%s", buffer);
 
    return 0;
}


Output

Sum of 10 and 20 is 30

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Time Complexity: O(n), where n is the number of elements being stored in buffer.
Auxiliary Space:  O(n), where n is the number of elements being stored in buffer.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments