format strings c code example

Example 1: format specifier fro float in printf

printf("%0k.yf" float_variable_name)

Here k is the total number of characters you want to get printed. k = x + 1 + y (+ 1 for the dot) and float_variable_name is the float variable that you want to get printed.

Suppose you want to print x digits before the decimal point and y digits after it. Now, if the number of digits before float_variable_name is less than x, then it will automatically prepend that many zeroes before it.

Example 2: c printf

/* printf example */
#include <stdio.h>

int main()
{
   printf ("Characters: %c %c \n", 'a', 65);
   printf ("Decimals: %d %ld\n", 1977, 650000L);
   printf ("Preceding with blanks: %10d \n", 1977);
   printf ("Preceding with zeros: %010d \n", 1977);
   printf ("Some different radices: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
   printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
   printf ("Width trick: %*d \n", 5, 10);
   printf ("%s \n", "A string");
   return 0;
}

Example 3: printf format specifiers c

/* printf example in C */
#include <stdio.h>

int main()
{
   printf ("Characters: %c %c \n", 'a', 65);
   printf ("Decimals: %d %ld\n", 1977, 650000L);
   printf ("Preceding with blanks: %10d \n", 1977);
   printf ("Preceding with zeros: %010d \n", 1977);
   printf ("Some different radices: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
   printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
   printf ("Width trick: %*d \n", 5, 10);
   printf ("%s \n", "A string");
  
   return 0;
}


//*******

Characters: a A
Decimals: 1977 650000
Preceding with blanks:       1977
Preceding with zeros: 0000001977
Some different radices: 100 64 144 0x64 0144
floats: 3.14 +3e+000 3.141600E+000
Width trick:    10
A string

Example 4: c++ char print width

/*
OUTPUT
char variable value: Programming
-----------------------------------------------------
[%s]       |Programming|
[%10s]     |Programming|
[%15s]     |    Programming|
[%-15s]    |Programming    |
[%15.5s]   |          Progr|
[%-15.5s]  |Progr          |
-----------------------------------------------------
*/

// NOTE: Specifically used for char data-types (not strings)

char str[]="Programming";    // Length = 11  

std::cout << "[%s]       |";
printf("%s",str);      // Display Complete String  
std::cout << "|\n";

std::cout << "[%10s]     |";
printf("%10s",str);    // 10 < Length: Display Complete String  
std::cout << "|\n";

std::cout << "[%15s]     |";
printf("%15s",str);    // 15 > Length: Displays Complete String with 4 spaces Alignment:Right  
std::cout << "|\n";

std::cout << "[%-15s]    |";
printf("%-15s",str);   // Same as Above But Left Aligned
std::cout << "|\n";

std::cout << "[%15.5s]   |";
printf("%15.5s",str);  // 15-5 = 10 spaces and show first 5 characters Align : R    
std::cout << "|\n";

std::cout << "[%-15.5s]  |";
printf("%-15.5s",str); // 15-5 = 10 spaces and show first 5 characters Align : L  
std::cout << "|\n";