Formatted I/O in C

Formatted input and output refer to input and output data that has been arranged in a particular format. C provides printf() and scanf() functions for formatted output and formatted input respectively. These functions accept format specification string and list of variables as parameters.

The format specification string is a string that specifies the data type of each variable to be input or output, and the size or width of input or output.

  • printf() / formatted output

The general form of printf() function is:

// prototype
int printf(const char *control_string, arg1, arg2,........argn);

control_string consists or following three type of items.

  1. Characters that will be printed to the screen as they appear.
  2. Format specification that defines the output format for displaying each argument.
  3. Escape sequence characters such as \n, \t, \b, etc.

A simple format specification has the following form:

%[flag][width].[precision][length]type-specifier

printf() function returns the number of characters written to the output console, and returns a negative number on failure. This can be used to test the success or failure of printf() function.

The table below shows basic integer, floating point, character, and string format specifications.

Data TypeFormat SpecificationDescription
Integer%[flag]wdTo print 45 in an space of 10, we can write %10d, where flag is default. On default, content will be right alligned. For control string %-10d, content will be left alligned. To display sign of an integer + flag can be used.
Floating Point%[flag]w.pf (normal form)
%[flag]w.pe (exponential, scientific format)
Precision here is total numbers after decimal point. and width is total width.
Character%[flag]wcTo display single character within a given space.
String%[flag]w.psw is total display space, and p is total string to be clipped from given string. It starts clipping from leftmost.
Control character formation in C

The followings are commonly used control characters.

Control CharacterMeaning
%cCharacter
%dDecimal Integer
%eFloating point value in exponent form
%fNormal floating point value
%gfloating point value
%hShort Integer
%iSigned decimal integer
%lFor long integers or double
%LFor Long Double
%oOctal integer without leading zero
%sString
%uUnsigned decimal integer
%xhexadecimal integer without leading 0x
Control characters in C

  • scanf() / formatted input

It means scan formatted input from standard input devices. It writes data into given arguments. It has the following form:

// prototype
int scanf(const char *control_string, &arg1, &arg2,........&argn);

The control_string may contain

  1. Field (or format) specifications consists of conversion character %, a data type character(or specifier), and the optional number specifying the field width.
  2. Blanks, tabs, and new lines.

scanf() function returns the number of variables read successfully. If it fails it returns negative number.

The control string formation is similar to the printf() function.

Complete Example of Formatted I/O:

/*
    Program test for Formatted I/O in C
*/

#include <stdio.h>
#include <conio.h>

int main(){
    int i = 10, i_read;
    float f = 123.456789, f_read;
    char c = 'c', c_read;
    char s[20] = "original", s_read[20];

    printf("Enter integer:");
    scanf("%d", &i_read);
    printf("Enter floating point value:");
    scanf("%f", &f_read);
    printf("Enter character:");
    // keep space before %c to avoid \n to feed for c_read
    scanf(" %c", &c_read);
    printf("Enter string(no space):");
    // this does not accept space, no need of &
    scanf("%s", s_read);

    // print right alligned table with each column of space 15
    printf("Right-Aligned table:\n");
    printf("%15s%15s%15s%15s\n", "Integer", "Floating", "Character", "String");
    printf("%15d%15f%15c%15s\n", i, f, c, s);
    printf("%15d%15f%15c%15s\n", i_read, f_read, c_read, s_read);


    printf("\n\nLeft-Aligned table:\n");
    printf("%-15s%-15s%-15s%-15s\n", "Integer", "Floating", "Character", "String");
    printf("%-15d%-15f%-15c%-15s\n", i, f, c, s);
    printf("%-15d%-15f%-15c%-15s\n", i_read, f_read, c_read, s_read);

    printf("\n\nAdditional flag + precision table:\n");
    printf("%-15s%-15s%-15s%-15s\n", "Integer", "Floating", "Character", "String");
    printf("%-+15d%-15.2f%-15c%-15.3s\n", i, f, c, s);
    printf("%-+15d%-15.3f%-15c%-15.3s\n", i_read, f_read, c_read, s_read);
    printf("%-+15d%-15.3e%-15c%-15.4s\n", i_read, f_read, c_read, s_read);
    printf("%-+15o%-15.3e%-15c%-15.6s\n", i_read, f_read, c_read, s_read);
    printf("%-+15x%-15.3e%-15c%-15.8s\n", i_read, f_read, c_read, s_read);
    return 0;
}

Sample Output:

Enter integer:34567
Enter floating point value:1234.567891
Enter character:s
Enter string(no space):bitslord
Right-Aligned table:
        Integer       Floating      Character         String
             10     123.456787              c       original
          34567    1234.567871              s       bitslord


Left-Aligned table:
Integer        Floating       Character      String
10             123.456787     c              original
34567          1234.567871    s              bitslord


Additional flag + precision table:
Integer        Floating       Character      String
+10            123.46         c              ori
+34567         1234.568       s              bit
+34567         1.235e+003     s              bits
103407         1.235e+003     s              bitslo
8707           1.235e+003     s              bitslord

Process returned 0 (0x0)   execution time : 15.484 s
Press any key to continue.