The sprintf() Function

Aside from being one of the most popular text-output functions in the C language, printf() is the most powerful. It can format all sorts of variables in unique ways, with padding and alignment options that even veteran C programmers can't recite from memory.

The printf() function isn't alone. It has many siblings and cousins that also harness its formatting power. One of the most useful variations is sprint().

What the sprint() function does is save formatted output, just like you get from a printf() function, into a buffer. Here's the format:

sprintf(buffer,format,variables);

In the preceding line, buffer is a char array into which the formatted output is stored. The rest of the arguments are identical to printf(). format is a formatting string: It uses text, escape sequences, and conversion characters. The list of variables and immediate values stuffed into the formatting string are represented by variables, as shown in the following code.

#include <stdio.h>
int main()
{
    char birthday[12];
    int day,month,year;
    printf("Enter your birth month (1-12): ");
    scanf("%d",&month);
    printf("Enter your birth day: ");
    scanf("%d",&day);
    printf("Enter your birth year: ");
    scanf("%d",&year);
    sprintf(birthday,"%d/%d/%d",month,day,year);
    printf("I shall wish you a happy birthday on %s\n",
        birthday);
    return(0);
}

The above code illustrates a sample program that uses sprint() to save a formatted date as a string. Values from the month, day, and year variables are placed into the standard date format and are then saved by the sprint() function into the birthday buffer. The printf() statement then displays the result.

The best way to put sprint() to work is to store complex numbers and formatted output for later display or manipulation. For example, you could use sprint() instead of printf() and then place code elsewhere in the program to confirm that the output is proper.

Regardless of how the sprint() function is used, you'll find it a valuable tool to keep handy in your programming tool chest.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com