17.2 – Formatted Console I/O – Part-2

by subbu on October 6, 2014

sprintf() function (Turbo C)

It is the formatted output function, used to print the formatted data onto a string rather onto the console output device. It accepts the target string, format string and list of identifiers as arguments and returns an integer as printf() statement.

printf("empno:%d\nName:%s\nPlace:%s\nPin:%ld",empno,name,place,pin);

It prints the details of employee onto the console output device

sprintf(str,"empno:%d\nName:%s\nPlace:%s\nPin:%ld",empno,name,place,pin);

It writes the details of employees on to string “str” rather monitor

#include<stdio.h>
int main()
{
 char str[150];
 int empno=1005;
 char name[20]="Mr.black";
 char place[20]="kavali";
 long int pin=524201;
 printf("Details of an Employee:\n");
 printf("empno:%d\nName:%s\nPlace:%s\nPin:%ld",empno,name,place,pin);
 return 0;
}

Output:
Details of an Employee:
empno:1005
Name:Mr.black
Place:kavali
Pin:524201

printf() in C language

In the above example the printf() function prints the formatted data directly onto the monitor.

#include<stdio.h>
int main()
{
 char str[150];
 int empno=1005;
 char name[20]="Mr.black";
 char place[20]="kavali";
 long int pin=524201;
 sprintf(str,"empno:%d\nName:%s\nPlace:%s\nPin:%ld",empno,name,place,pin);
 printf("Details of an Employee:\n");
 printf("%s",str);
 return 0;
}

Output:
Details of an Employee:
empno:1005
Name:Mr.black
Place:kavali
Pin:524201

sprintf() function in C language

In the above example the sprintf() function prints the formatted data onto the string “str” which is again printed onto the monitor using printf() statement.

sscanf() function (turbo C)

It is the formatted input function used to read the data from a complex string and stores into individual variables.

Here the complex string, format string and list of addresses of variables are send as argument and an integer is returned as scanf()

sscanf(str,"%d%s%s%ld",&empno,name,place,&pin);

It reads the details from the string “str” and stores into individual variables

#include<stdio.h>
int main()
{
 char str[150]="1002 Mr.Black Kavali 524201"; /* complex string */
 int empno;
 char name[20];
 char place[20];
 long int pin;
 sscanf(str,"%d%s%s%ld",&empno,name,place,&pin);
 printf("Details of Employee:\n");
 printf("empno:%d",empno);
 printf("\nName:%s",name);
 printf("\nPlace:%s",place);
 printf("\nPin code:%ld",pin);
 return 0;
}

Output:
Details of Employee:
empno:1002
Name:Mr.Black
Place:Kavali
Pin code:524201

In the example, string “str” has details of an employee, sscanf() read the details from “str” in a sequence and stored into variables. Here the data in the complex string, format specifiers and the type of variables must match in a sequence.

sscanf() function in C language

Previous post:

Next post: