Tuesday, September 27, 2011

Formatted Strings in ANSI C

A formatted element can be defined as:

%[flags][width][.precision][length]specifier

The elements between between square brackets are optional.

1. Flags

-   Uses left justification instead of right justification.
Example:
#include<stdio.h>

int main(void)
{
   printf("Right justification: %10d\n",42);
   printf("Left justification: %-10d\n",42);
   return 0;
}
/*Output:
Right justification:         42
Left justification: 42
*/
 Forces the display of the number's sign (normally, the plus sign is not displayed, only the minus sign being displayed by default).
Example:
#include<stdio.h>

int main(void)
{
   printf("%+d\n",10);
   printf("%d\n", 10);
   return 0;
}
/*Output
+10
10
*/
blank (space) - If the number is positive, there will be a space placed before the number is formatted
Example:
#include<stdio.h>

int main(void)
{
   printf("% d",10);
   return 0;
}
/*Output
 10
*/
# -If used with o,x or X the result will be preceded by 0, 0x or 0X. If used with e, E,f, g,G the result contain a decimal point, even if there are no digits after him.
Example:
#include<stdio.h>

int main(void)
{
   printf("Octal                   : %#o\n",10);
   printf("Hexadecimal             : %#x\n",10);
   printf("Hexadecimal             : %#X\n",10);
   printf("Float                   : %#f\n",10.0f);
   printf("Scientific lowercase    : %#e\n",10.0f);
   printf("Scientific uppercase    : %#E\n",10.0f);
   printf("Shortest form lowercase : %#g\n",10.0f);
   printf("Shortest form uppercase : %#g\n",10.0f);
   return 0;
}
/*Output
Octal                   : 012
Hexadecimal             : 0xa
Hexadecimal             : 0XA
Float                   : 10.000000
Scientific lowercase    : 1.000000e+01
Scientific uppercase    : 1.000000E+01
Shortest form lowercase : 10.0000
Shortest form uppercase : 10.0000
*/
0 - Left-pads the number with zeroes (0) instead of spaces when padding it specified.
Example:
#include<stdio.h>

int main(void)
{
   printf("%010d",10);
   return 0;
}
/*Output
0000000010
*/
2. Width
The width represents the minimum number of characters. If the formatted element's size is smaller than the specified width, the element is left-padded with blanks (spaces). It's good to know that if the element has its size greater than the specified width, he will not be truncated.
Example:
#include<stdio.h>

int main(void)
{
   printf("%1d will not be truncated\n",10000);
   printf("%15d\n",10000);
   return 0;
}
/*Output
10000 will not be truncated
          10000
*/

If the width is not specified in the format string (".*"), an additional integer value is needed as an argument before.
Example:
#include<stdio.h>

int main(void)
{
   printf("The meaning of life is %*d", 5, 42);
   return 0;
}
/*Output
The meaning of life is     42
*/
3. Precision
For decimal data types specifiers (d,i,o,u,x,X), precision specifies the minimum number of digits to be written. If the value to be written is shorter when compared to the precision value, the result is padded with zeros. Otherwise (if the value is longer when compared to the precision value), the result is not truncated.

For the character type (c), it has no effect.
Example:
#include<stdio.h>

int main(void)
{
   printf("\n%1.1c will not be affected",'I');
   return 0;
}
/*Output
I will not be affected
*/
For floating point data types specifiers (e,E,f, g, G) the precision represents the number of digits to be printed after the decimal point.
Example:
#include<stdio.h>

int main(void)
{
   printf("\n%1.1f",3.141f);
   printf("\n%1.1e",3.141f);
   printf("\n%1.1E",3.141f);
   printf("\n%1.1g",3.141f);
   printf("\n%1.1G",3.141f);
   return 0;
}
/*Output
3.1
3.1e+00
3.1E+00
3.1
3.1
*/
For strings (s), the precision represents the maximum number of characters to be written.
Example:
#include<stdio.h>

int main(void)
{
   printf("\n%1.3s","The bird is the word");
   return 0;
}
/*Output
The
*/
When the precision is not specified, it's considered 0.

4. Length
h - the argument is interpreted as short (available for d,i,o,u,x,X)
l - the argument is interpreted as long (for d,i,o,u,x,X). For the specifiers c or s, the character/string will become wide.
L - the argument is interpreted as long (for e,E,f,g,G)
    5. Specifiers
    • Common specifiers
      • c - outputs an character (char)
      • d or i - outputs an signed integer (int)
      • u - outputs an unsigned integer (unsigned int)
      • f - outputs an floating point number (float)
      • s - outputs an string (char[] or char*)
      • p - outputs an pointer address
    • Less common specifiers
      • e - outputs a number in the mantise/exponent form using e (example: 3e023)
      • E - outputs a number in the mantise/exponent form using E (example: 5E-23)
      • g - outputs the shortest form between %f and %e (as in number of characters)
      • G - outputs the shortest form between %f and %E (as in number of characters)
      • n - does not output the argument
    • Base-conversion specifiers
      • o - outputs an unsigned decimal in base-8 (octal base)
      • x - outputs an unsigned decimal in base-16 (hexadecimal base) using the x character
      • X - outputs an unsigned decimal in base-16 (hexadecimal base) using the X character
    Example:
    #include<stdio.h>
    
    int main(void)
    {
       printf("Character              : %c  \n",'a');
       printf("Integer                : %d  \n",32);
       printf("Short integer          : %hd \n",32);
       printf("Long integer           : %ld \n",32L);
       printf("Unsigned integer       : %u  \n",32U);
       printf("Short unsigned integer : %hu \n" 32U);
       printf("Long unsigned integer  : %lu \n",32UL);
       printf("Float                  : %f  \n",32.0f);
       printf("Double                 : %f  \n",32.0);
       printf("Long double            : %Lf \n",32.0L);
       printf("String                 : %s  \n","word");
       return 0;
    }
    /*Output
    Character            : a
    Integer              : 32
    Short integer        : 32
    Long integer         : 32
    Unsigned integer     : 32
    Long unsigned integer: 32
    Float                : 32.000000
    Double               : 32.000000
    Long double          : 32.000000
    String               : word
    */
    6.Special characters
    \n - newline (end current line)
    \t - horizontal tab (inserts tab, leaving blank space)
    \v - vertical tab  (ends current line and continues on the next line at the same position)
    \b - backspace (deletes last character)
    \r - carriage return (returns the cursor at the beginning of the line)
    \f - form-feed (creates a page break for electronic documents. It is seldom used in modern environments)
    \a - alert
    \\ - backslash
    \? - question mark
    \' - single quotation mark
    \" - double quotation mark
    \ooo - octal number
    \xhhh - hexadecimal number
    \0 - null character
    Example:
    #include<stdio.h>
    
    int main(void)
    {
        /*The text who will follow this call will be on a new line*/
        printf("The bird is the word\n");
        /*Inserts a horizontal tab before writing the text*/
        printf("\tThe bird is the word");
        /*Ends the current line and continues writing at the same position*/
        printf("\vThe bird is the word\n");
        /*Deletes the 'r' character from word*/
        printf("The bird is the wor\bd\n");
        /*Returns the cursor the begining of the line*/
        printf("The bird is the word\rBird bird bird!");
        /*Produces an buzz-like sound*/
        printf("\nAlert\a\n");
        /*Backslash, question mark and single/double quotation marks require
        a backslash in order to be interpreted corectly*/
        printf("\\This is a backslash.Do you have any questions\?\n");
        printf("I've heard \"The bird\" is the \'word\'");
        return 0;
    }
    /*Output
    The bird is the word
     The bird is the word
                                The bird is the word
    The bird is the wod
    Bird bird bird! word
    Alert
    \This is a backslash.Do you have any questions?
    I've heard "The bird" is the 'word'
    */

    QuestionWhat tips & tricks do you know related to formatted strings?

    References:
    http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output

    No comments:

    Post a Comment

    Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

    Related Posts Plugin for WordPress, Blogger...
    Recommended Post Slide Out For Blogger