Wednesday, February 10, 2016

C Format Specifiers for printf and scanf

Format SpecifierAssociated DatatypeDescription
%ccharUsed to format single character
%d or %iintUsed to format a signed integer
%uintUsed to format an unsigned integer in decimal form
%ointUsed to format an unsigned integer in octal form
%x or %XintUsed to format an unsigned integer in hex form
%hintUsed to format an short integer
%e or %Efloat or doubleUsed to format a float or double in exponential form
%ffloat or doubleUsed to format a float or double in decimal format
%schar[]Used to format a string/character sequence

Example of Print Format Specifiers

Now that we know how to print any data type, let's take a look at a simple example.
  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5. int i = 30;
  6. char c = 'z';
  7. float f = 5.67;
  8. char s[] = "This is a string";
  9. printf("i=%d, c=%c, f=%f, s=%s", i,c,f,s);
  10. return 0;
  11. }
  12.  
  13. Output:
  14. i=30, c=z, f=5.670000, s=This is a string
In this program, we've got some familiar variable declaration; one int, one char one float and one string (char[]). After declaring and assigning values to the variables, we invoked a printf statement which print contents between two double inverted commas to the standard output or the screen. The contents are written in the screen using print format specifiers, which replace the values of the variables that appears after closing '"'.

Here %d is replaced by decimal value of the variable 'i' which is 30, %c is replaced by the character stored in variable 'c', %f is replaced by the floating point value with variable 'f' and %s is replaced by the string represented by array 's'. Note the order of the print format specifiers are same as the order of variables appearing in the printf statement. The order of declaration does not matter as long as you declare the variables before you print them.

No comments: