Difference between printf and sprintf in c programming language

Here we are going to learn about printf and sprintf statements in c programming language, when and how they are used? What are their parameters and what they return?

printf

printf is used to print text (string/ character stream) or/and values on standard output device.

Here is the syntax

int printf(const char *format, ...);

Here,

  • format provides the format of the text string which is going to print on the output device with the help of format specifiers like %s, %d, %f etc.
  • ... provides the list of arguments to be print.
  • Return type int returns total number of printed characters on the output screen.

A simple program to print "Hello"

#include <stdio.h>

int main()
{
    printf("Hello");

    return 0;
}

Output

Hello

Program to print Name and Age

#include <stdio.h>

int main()
{
    printf("My name is %s, I am %d years old\n","Mike",23);

    return 0;
}

Output

My name is Mike, I am 23 years old

Program to get and print return value of printf

#include <stdio.h>

int main()
{
    int n;
    
    n=printf("Hello world!");
    
    printf("\nTotal number of printed characters are: %d\n",n);

    return 0;
}

Output

Hello world!
Total number of printed characters are: 12

sprintf

sprintf is used to send (copy) formatted text (string/ character stream) to a string.

Here is the syntax

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

Here,

  • char *str - Is character array in which formatted text will be sent (copied).
  • format provides the formatted text with the help of format specifiers.
  • ... provides the list of arguments to be print.
  • Return type int returns total number of copied (sent) characters into the char *str.

A simple program to copy Name, age with formatted text in a character array

#include <stdio.h>

int main()
{
    char str[100];
    
    sprintf((char*)str,"My name is %s, I am %d years old.","Mike",23);
    
    printf("Text is: %s\n",str);

    return 0;
}

Output

Text is: My name is Mike, I am 23 years old.

A program to get and print return value of sprintf

#include <stdio.h>

int main()
{
    char str[100];
    int n;
    
    n=sprintf((char*)str,"My name is %s, I am %d years old.","Mike",23);
    
    printf("Text is: %s\n",str);
    printf("Total number of copied characters are: %d\n",n);

    return 0;
}

Output

Text is: My name is Mike, I am 23 years old.
Total number of copied characters are: 35

Reference: https://en.wikipedia.org/wiki/Printf_format_string




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.