Standard IO: Formatted IO

Standard Input/Output
  • The header file stdio.h

    • #include<stdio.h> is a preprocessor directive
    • stdio.h is the header file
      • It contains macros for many I/O functions
      • printf(), scanf(), putch(), getch(), puts(), gets() functions require the macros in stdio.h
  • printf()

    • To display data on the standard output console (terminal)
    • Syntax:
      • printf(“control string”, argument list);
    • Argument list consists of constants, variables, expressions or functions separated by comas
    • Control String consists of:
      • Text characters
      • Format commands: % sign + format code
      • Special characters: \\, \”, %%
  • Format codes

    Format printf() scanf()
    Single Character %c %c
    String %s %s
    Signed decimal integer %d %d
    Floating point (decimal notation) %f %f or %e
    Floating point (decimal notation) %lf %lf
    Floating point (exponential notation) %e %f or %e
    Floating point ( %f  or %e , whichever is shorter) %g  
    Unsigned decimal integer %u %u
    Unsigned hexadecimal integer (uses “ABCDEF”) %x %x
    Unsigned octal integer %o %o
  • printf modifiers

    • Field width modifier
      • It’s an integer, defines minimum field with for displaying the data
    • Alignment modifier (‘-’)
      • The item will be printed beginning from the leftmost position of its field
    • Precision modifier
      • It indicates the maximum number of digits to be printed after the floating point
    • Zero padding modifier (‘0’)
      • Used to pad ‘0’ to values if there are more space for its displaying field (field width)
    • Example from Wikipedia
    • scanf()

      • Used to accept data from standard Input
      • General format of scanf() function
        • scanf(“control string”, arg. list)
        • The format codes used in printf()are the same as in the scanf(), with some notices
            printf() scanf()
          Argument list uses variable names, constants, symbolic constants  and expressions
          uses pointers to variables 
          %g Yes No
          %f and %e Are different Are the same
  • Ses1FormattedOutput Source Code

    #include <stdio.h>

    #include <stdlib.h>


    int main(int argc, char *argv[]) {

        printf("|%05d|%-20s|%15.2f|\n", 1, "Mr. John", 200.0);

        printf("|%05d|%-20s|%15.2f|\n", 2, "Mr. Smith", 200.1234);

        printf("|%05d|%-20s|%15.2f|\n", 200, "Mrs. Alice", 200.222);

        return 0;