Formatted Mode console

C library has two library functions scanf() and printf() for doing all formatted console input output works. scanf is to read formatted input and printf is to write formatted output.

Formatted output printf

printf takes one fixed argument and can take variable additional arguments. First argument is the format string. Additional arguments depends of formatting string. User has to provide the elements in the same sequence as the format string has been given. printf scans the formatting string and replaces all the %<element> with the text equivalent of the arguments given. This buffer then goes for writing to the output console device. It returns the number of bytes written to the console.

Syntax

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

Formatted inputs scanf

scanf takes one fixed argument and can take variable additional arguments. First argument is the format string. Additional arguments depends of formatting string. User has to provide the elements in the same sequence as the format string has been given. scanf reads console input file and scans input buffer as per formatting string and whenever it finds %<element> it converts the element and stores in the address given in the additional arguments. User has to provide the reference of the variables in the arguments in order to receive type objects from file. It returns the number of successful arguments converted successfully.

Syntax

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

Formatted Mode example

int main(int argc, char *argv[])
{
  char first_name[50];
  char last_name[50];
  int std;
  int roll;
  char grade;
  float score;
  
  printf ("Entering data for student database\n");
  /* Taking all formatted inputs */
  printf ("First name : ");
  scanf ("%s", first_name);
  printf ("Last name : ");
  scanf ("%s", last_name);
  printf ("Class/Std [1-12]: ");
  scanf ("%d", &std);
  printf ("Enrollment number : ");
  scanf ("%d", &roll);
  printf ("Score : ");
  scanf ("%f", &score);
  printf ("Grade [A-D] : ");
  fflush(stdin);
  scanf ("%c", &grade);

  /* Displaying all formatted outputs */  
  
  printf ("First name : %s\n", first_name);
  printf ("Last name : %s\n", first_name);
  printf ("Class/Std : %d\n", std);
  printf ("Roll number : %d\n", roll);
  printf ("Score : %.2f %c\n", score, '%');
  printf ("Grade : %c\n", grade);
}

Output

Entering data for student database
First name : John
Last name : Carter
Class/Std [1-12]: 1
Enrollment number : 2
Score : 85.6
Grade [A-D] : A
First name  : John
Last name   : John
Class/Std   : 1
Roll number : 2
Score       : 85.60
Grade       : A

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

#