Formatted I/O in C programming



Formatting Output with printf

Every printf call contains a format control string that describes the output format.

The format control string consists of conversion specifiers, flags, field widths, precisions and literal characters.

Syntax:


    printf( format-control-string, other-arguments );

The format-control-string describes the output format, and other-arguments (which are optional) correspond to each conversion specification in format-control-string.

Example using integer conversion specifiers.

   
    // Using the integer conversion specifiers
    #include <stdio.h>
    int main( void ) { 
    printf( "%d\n", 455 );
    printf( "%i\n", 455 ); // i same as d in printf
    printf( "%d\n", +455 ); // plus sign does not print
    printf( "%d\n", -455 ); // minus sign prints
    printf( "%hd\n", 32000 );
    printf( "%ld\n", 1000000000L ); // L suffix makes literal a long 
    printf( "%o\n", 455 ); // octal
    printf( "%u\n", 455 );
    printf( "%u\n", -455 );
    printf( "%x\n", 455 ); // hexadecimal with lowercase letters
    printf( "%X\n", 455 ); // hexidecimal with uppercase letters
    } // end main

    Output:
    455
    455
    455
    -455
    32000
    1000000000
    707
    455
    4294966841
    1c7
    1C7

Printing Strings and Characters

  • Conversion specifier c requires a char argument.
  • Conversion specifier s requires a pointer to char as an argument.
   
    // Using the character and string conversion specifiers
    #include <stdio.h>
    int main( void ) { 
    char character = 'A'; // initialize char
    char string[] = "This is a string"; // initialize char array
    const char *stringPtr = "This is also a string"; // char pointer
    printf( "%c\n", character );
    printf( "%s\n", "This is a string" );
    printf( "%s\n", string );
    printf( "%s\n", stringPtr );
    } // end main

    Output:
    A
    This is a string
    This is a string
    This is also a string

Reading Formatted Input with scanf

Precise input formatting can be accomplished with scanf. Every scanf statement contains a format control string that describes the format of the data to be input.


    scanf( format-control-string, other-arguments );

format-control-string describes the formats of the input, and other-arguments are pointers to variables in which the input will be stored.

   
    // Reading input with integer conversion specifiers
    #include <stdio.h>
    int main( void ) { 
    int a, b, c, d, e, f, g; 
    puts( "Enter seven integers: " );
    scanf( "%d%i%i%i%o%u%x", &a, &b, &c, &d, &e, &f, &g );
    puts( "\nThe input displayed as decimal integers is:" );
    printf( "%d %d %d %d %d %d %d\n", a, b, c, d, e, f, g );
    } // end main

    Output:
    Enter seven integers:
    -20 -30 020 0x20 20 20 20
    The input displayed as decimal integers is:
    -20 -30 16 32 16 20 32

Ads Right