Back to C++
2026-02-215 min read

Print functions (C++)

Learn Print functions (C++) step by step with clear examples and exercises.

Title: Mastering Print Functions in C++ (C++23)

Why This Matters

Print functions are an essential part of any C++ program, enabling developers to display output on the console. They play a significant role in debugging, testing, and creating user interfaces. In this lesson, we will delve deeper into the print functions introduced in C++23, which offer enhanced functionality and efficiency over previous versions.

The Advantages of Print Functions

  1. Simplicity: Print functions allow you to output various data types without having to create or manipulate streams explicitly.
  2. Readability: The syntax for using print functions is simpler and more intuitive, making your code easier to understand and maintain.
  3. Performance: Print functions are optimized for performance, providing faster output compared to the traditional stream-based approach in some cases.
  4. Error Handling: Unlike traditional I/O operations, print functions do not throw exceptions when an error occurs. Instead, they produce a default output or behave unexpectedly if given invalid arguments.

Prerequisites

Before diving into print functions, you should have a solid understanding of:

  • Basic C++ syntax and semantics
  • Standard library headers (``)
  • Stream-based I/O in C++
  • Data types and their properties in C++
  • Control structures such as loops and conditionals

Understanding Standard Library Headers

To use print functions, you need to include the `` header at the beginning of your code:

#include <iostream>

Core Concept

Print Functions in C++23 are part of the input/output library, which includes both stream-based I/O and print functions. The print functions provide a more straightforward way to output data compared to the traditional stream-based approach. They offer several advantages:

  1. Simplicity: Print functions allow you to output various data types without having to create or manipulate streams explicitly.
  2. Readability: The syntax for using print functions is simpler and more intuitive, making your code easier to understand and maintain.
  3. Performance: Print functions are optimized for performance, providing faster output compared to the traditional stream-based approach in some cases.
  4. Error Handling: Unlike traditional I/O operations, print functions do not throw exceptions when an error occurs. Instead, they produce a default output or behave unexpectedly if given invalid arguments.

Placeholders and Formatting

Print functions use placeholders to indicate where to insert the values in the output string. The most common placeholder is {}, which can be used with various data types:

int num = 42;
std::print("The value of num is: {}", num); // Print an integer using placeholders
float pi = 3.14159;
std::print("The value of pi is approximately: {:.6f}", pi); // Print a floating-point number with precision

Worked Example

Let's write a simple program that demonstrates using print functions:

#include <iostream>
#include <vector>

int main() {
std::print("Hello, World!\n"); // Print a string with newline
int num = 42;
std::print("The value of num is: {}", num); // Print an integer using placeholders
float pi = 3.14159;
std::print("The value of pi is approximately: {:.6f}", pi); // Print a floating-point number with precision

std::vector<int> numbers = {1, 2, 3};
for (const auto& number : numbers) {
std::print("Numbers in the vector are: {}", number);
}

return 0;
}

Common Mistakes

  1. Forgetting to include the header: Make sure you include `` at the beginning of your code to use print functions.
  2. Incorrect usage of placeholders: Ensure that the number and order of placeholders match the arguments passed to the function.
  3. Not understanding error handling: Print functions do not throw exceptions, so if an error occurs (e.g., invalid argument type), your program will continue executing without any indication of the issue.
  4. Improper use of std::print with non-supported data types: When using unsupported data types, print functions may produce unexpected results or default string representations.
  5. Ignoring the order of arguments and placeholders: The order of arguments passed to std::print should match the order of placeholders in the format string.
  6. Not handling exceptions when working with user input: When using functions like std::cin, it's important to handle exceptions that may occur, such as invalid input or resource exhaustion.

Common Mistakes (Part 2)

  1. Not validating user input: It's essential to validate user input to ensure that the data provided is in the expected format and range.
  2. Ignoring precision and width specifications: When formatting floating-point numbers, it's crucial to set appropriate precision and width values to achieve the desired output.
  3. Not testing your code thoroughly: Always test your code with various inputs to ensure that the output is correct and that print functions are working as expected.

Practice Questions

  1. Write a program that uses print functions to output the sum and product of two integers entered by the user.
  2. Modify the worked example to output the maximum and minimum values between three floating-point numbers using print functions.
  3. How would you use print functions to create a simple calculator with addition, subtraction, multiplication, and division operations?
  4. Write a program that uses print functions to perform basic file I/O operations like reading from and writing to files.
  5. Create a program using print functions to implement a simple command-line interface for managing a list of tasks.

FAQ

  1. Why are print functions better than traditional stream-based I/O? Print functions offer simplicity, readability, improved performance, and error handling compared to the traditional stream-based approach.
  2. Can I use print functions with older versions of C++? No, print functions were introduced in C++23, so they are not available in earlier versions of the language.
  3. What happens if I try to use a non-supported data type with print functions? Print functions will output the default string representation of the data type, which may not be what you expect.
  4. How can I handle exceptions when working with user input using print functions? To handle exceptions when working with user input, you should use functions like std::cin and catch any potential exceptions that may occur during input processing.
  5. What are some best practices for using print functions in C++? Best practices include using placeholders for clarity, validating user input, handling exceptions, and testing your code thoroughly to ensure correct output.
Print functions (C++) | C++ | XQA Learn