Home C C++ Java Python Perl PHP SQL JavaScript Linux Selenium QT Online Test

Formatted Input Output using printf() & scanf()

These two commonly used functions for Input/output and both are library function of C. The printf() prints on screen while scanf() is used to take input from standard input like keyboard.

The printf()Function

  • The printf() function must be supplied with a string, followed by any values that are to be inserted into the string during printing. Syntax for printf : printf(string, expr1, expr2, ..);
  • The format string may contain both ordinary characters and conversion specifications, which begin with the % character.
  • A conversion specification is a placeholder representing a value to be filled in during printing.
         - %d is used for int values
         - %f is used for float values
         - %c is used to char values

Example of printf() Function

#include <stdio.h>

int main()
{
int noX, noY;
float xx, yy;
noX = 17;
noY = 19;
xx = 37.1234f;
yy = 777.0f;
printf("noX = %d, noY = %d, xx = %f, yy = %f\n", noX, noY, xx, yy);
return 0;
}

Output :

noX = 17, noY = 19, xx = 37.123402, yy = 777.000000

Key points to remember about printf()

1. Compilers aren't required to check that the number of conversion specifications in a format string matches the number of output items.
2. Too many conversion specification doesn't give compiler error but we should take care of it -

printf("%d %d \n", xx); 
Here only single "%d" should be used.
3. Too few conversion specifications also doesn't give error but it should be taken care of -
printf("%d \n", ii, jj);
4. Compiler doesn't check for conversion specification. If the programmer uses wrong specification then the program's ouptut will be messed up - Suppose ii is int varaible and xx is char variable :
printf("%f %d ", ii, xx);
/* in place of %d programmer put %f and inplace of %c programmer put %d */

The scanf() function

  • scanf reads input according to a particular format.
  • A scanf format string may contain both ordinary characters and conversion specifications.
  • The conversions allowed with scanf are essentially the same as those used with printf.
  • In many cases, a scanf format string will contain only conversion specifications: only conversion specifications

Example of scanf()

#include <stdio.h>

int main()
{
int noX;
float noY;

printf("\n Enter noX & noY  - ");
scanf("%d%f",&noX,&noY);

printf("\n noX : %d, noY : %f", noX, noY);
return 0;
}