🖨️

Understanding Formatted Output with printf

Mar 20, 2025

Lecture on Formatted Output with printf

Overview

  • Discussion on printing formatted output using printf.
  • Comparison of printf with cout.
  • printf originates from C Standard I/O Library (<cstdio>).
  • Use of printf in other languages such as Java and C#.

Syntax of printf

  • Basic syntax: printf(format string, parameters...).
  • Format string contains format specifiers.
  • Each format specifier corresponds to a parameter.
  • Must include #include <cstdio> when using printf in C++.

Example and Explanation

  1. Basic Print

    • printf("What's up\n"); similar to cout << "What's up";
    • Moves cursor to the next line after printing.
  2. Using Format Specifiers

    • Example: printf("x: %d, y: %.3f\n", x, y);
      • %d: formats integers.
      • %.3f: formats floating-point numbers with 3 decimal precision.
    • Number of parameters must match the number of specifiers.

Detailed Explanation of Format Specifiers

  • %c for characters.
  • %d or %i for signed decimal integers.
  • %lld for long long integers.
  • %x for hexadecimal numbers.
  • %f for floating-point or double.
  • %s for C-style strings.
  • %% to print the percent character.

Alignment and Width

  • Default alignment is right.
  • Use - for left alignment.
  • Can specify width and fill characters.

Advanced Format Specifiers

  • %10d: allocates 10 spaces, right-aligned.
  • %010d: zero-padded, 10 spaces, right-aligned.
  • %-10d: left-aligned.

Printing Floating Point Numbers

  • Control precision and width using format specifiers.
  • Example: %.2f prints two decimal places.
  • Printing in scientific notation with %e.

Printing C++ Strings

  • Convert C++ strings to C strings using .c_str().
  • Example: printf("%20s", cppString.c_str());
  • Use %s for string printing.

Practical Usage Example

  • Demonstration of printing a formatted table using printf.
  • Example: aligning numbers and strings in a table format.

Conclusion

  • printf is a versatile tool for formatted output.
  • It's a standard in many programming languages.
  • Useful for creating neatly formatted tables in programs.
  • Upcoming lab exercise to utilize these concepts.