C++ Printf Function

C-Printf-Function-2.jpg

The C++ printf function is used to show messages or values on the screen. It comes from the C language but also works in C++. You can use it to print numbers, text, and characters in a nice format. It uses format specifiers like %d for numbers and %s for strings. In this post, you will learn how printf in C++ works with simple examples and tips. In this article, we will learn the printf() function in C++ in detail.

Table of Contents:

What is printf() in C++?

printf() is a function that is used to print the output to the console. It comes from the C language but is also available in C++ through the <cstdio> or <stdio.h> header. This makes it a versatile C++ output function.

Syntax of printf:

#include <cstdio>  // or #include <stdio.h>
int printf(const char *format, ...);

Parameters of printf() Function in C++ 

1. format: 

It is a string that contains the text to print and format specifiers for variables. It tells what text to print. Its type is const char*. 

Note: This parameter is required

Example:

printf("Hello, %s!\n", "World");

In the above example, “Hello, %s!\n” is the format string.

2. … (variable arguments)

It represents a variable number of additional arguments, which are also called variadic arguments. These variables correspond one-to-one with the format specifiers. Also, each type of argument should match the format specifier. This also helps us to understand how to use printf in C++ for dynamic output.

Example:

printf("Int: %d, Float: %.2f, Char: %c\n", 10, 3.14, 'A');

In the above example, 

  • 10 corresponds to %d
  • 3.14 corresponds to %.2f
  • ‘A’ corresponds to %c

Here is a basic C++ printf example for beginners.

Cpp

Output:

printf() Parameters

Explanation:

In the above example, 

  • %s is replaced by the string “Ali”.
  • %d is replaced by the integer 25.
  • \n adds a new line at the end.

What Does printf() Return in C++? 

The C++ printf function returns an integer. It returns the total number of characters that are printed successfully. But if an error occurs, it returns a negative number.

Example:

Cpp

Output:

printf() Return Value  

Explanation:

In this example, 

  • “Hello” has 5 characters
  • “,” has 1 character
  • space has 1 character
  • “World” has 5 characters
  • “!” has 1 character
  • “\n” has 1 character

Hence, 5 + 1 +1 + 5 + 1 + 1 = 14 characters

Note: printf in C++ counts all characters it prints, including spaces and \n.

Get 100% Hike!

Master Most in Demand Skills Now!

Syntax and Prototype of printf() Function in C++  

The prototype of the C++ printf function is declared in the <cstdio> library.

Syntax:

int printf(const char *format, ...);

In the above, 

  • int” is the return type of the function. Also, it tells how many characters were printed.
  • printf” is the name of the function. It is present in the C standard library, stdio.h in C, or in cstdio in C++.
  • . . . (ellipsis)“, this means that the function takes a variable number of arguments, which are the values that replace the format specifiers in the format string. Each argument must match the type of its corresponding format specifier.

Understanding Format Specifiers in C++ printf()

A format specifier is a code that starts with % and tells printf in C++ what type of value you want to print, like an integer, a float, or a string. These are essential for formatted printing in C++.

There are many components of a format specifier. These are as follows:

  1. Percent sign (%): It is the start of the format specifier
  2. Flags: They are special symbols that change how the output will look. for example, -, +, or 0.
  3. Width: It sets the minimum space that the value should take
  4. Precision: it controls how many decimal places to show for numbers or how many characters to print for the strings.
  5. Length modifier: It tells the size of the data, whether short or long.
  6. Conversion character: it is the main part that shows the type of data, like %d for integers, %f for floating-point numbers, or %s for strings.

Note: Apart from % and conversion character, the rest of them are optional. 

Flags

Flags are the extra symbols that you can add after the % sign in the format specifier. They mainly change the look of the output, i.e., how it will look

Let us discuss some common flags in C++.

  • – (minus sign): It left-aligns the output in the given space.
  • + (plus sign): It always shows the sign, i.e., + or – in front of the numbers.
  • 0 (zero): It fills the extra spaces with zeros.
  • space: If the number is positive, leave a space instead of a + sign.
  • # (hash): It adds a prefix for some number types. 

List of Common Format Specifiers for printf() in C++

Some common format specifiers in C++ are as follows:

Specifier Meaning Example Value
%d Integer (decimal) 25
%f Floating-point (decimal) 3.14
%.2f Float with 2 decimal places 3.14
%c Character ‘A’
%s String (text) “Ayaan”
%u Unsigned int (only positive) 100
%x Hexadecimal (lowercase) 255
%X Hexadecimal (uppercase) 255
%% Prints a percent sign %

Note: Use the correct format specifier that matches the data type you are printing, or else you will get the wrong output. 

How to Match Parameter Values with Format Specifiers in printf()

The parameter values are the actual data that you provide to fill in the format specifiers (%d, %s, etc.) in the format string. This is a crucial aspect to understand how to use printf in C++.

There are some rules for the parameter values in C++. These are as follows:

  • Match the number: You must give the values as there are format specifiers like %d, %s, etc. in the format string.
  • Match the order: the first value should go to the first specifier, and the second value should go to the second specifier.
  • Match the data type: Each value must be the correct type for its specifier. For example, %d needs an integer, and %s needs a string.
  • No missing values: Do not leave out any values. If you do it, the printf in C++ will print a garbage value
  • Avoid giving: Do not give more values than needed, as extra values will be ignored.

Difference Between printf() and sprintf() in C++

Both sprintf() and printf() return the value of the total number of characters written, excluding the null terminator.

1. printf()

The C++ printf function prints the formatted output to the screen.

For example:

Cpp

Output:

printf

Explanation:

In the above code, printf first formats and prints the message “You are 30 years old” without storing it in a separate variable first.

2. Sprintf

It prints the formatted output to a string in memory. It prints the output as a character array in memory. 

Note: Always use snprintf() instead of sprintf() to avoid crashes and security risks because it limits the number of characters written and prevents buffer overflows.

For example:

Cpp

Output:

Sprintf

Explanation: 

In the above code, the message is first stored in the msg, and then it is printed.

Here is a table that shows the key differences when considering C++ Printf vs Sprintf.

Feature printf() sprintf()
Purpose Prints formatted text to the console Writes formatted text to a char array (string in memory)
Output Location Console / Standard output (stdout) Memory buffer (char[])
Adds Null Terminator (\0) No, it’s just console output Yes, it adds a \0 at the end of the string
Buffer Overflow Risk No Yes, if the buffer is small
Use Case When you want to display formatted output When you want to store formatted output in a string
Example printf("Age: %d", 25); sprintf(buf, "Age: %d", 25);

printf vs cout in C++: Which One to Use and Why?

As C++ has the cout, many people still use printf() because of the following reasons:

  • printf() is from C: It is an old function from the C language. If anyone already knows C, it’s easier to keep using printf() in C++ also.
  • It gives good formatting: The C++ printf function makes it easy to control how the output will look.
  • Faster in Competitive Coding: printf() is usually faster than cout, so many coders use it in competitions.
  • Some Old Code Uses It: Older projects, codes, or C libraries still use the printf().
  • Useful for Tables and Clean Output: The C++ printf function is more controlled as it prints neat tables or aligned numbers.

Drawbacks and Limitations of Using printf() in C++

Despite its advantages, printf() also has some limitations. They are:

  • printf in C++ does not check if the data type matches the format specifier. If you use %d for a string by mistake, your program may print garbage output
  • For long or mixed outputs, the C++ printf function can get messy and hard to understand.
  • printf in C++ uses fixed format specifiers (like %d, %s, %f) which are limiting.
  • It is easy to make mistakes like the wrong specifier for a value and forgetting \n.
  • The C++ printf function does not work well with templates, namespaces, or streams like files.

How to Format Output Using printf() in C++

The printf in C++ uses the format string containing format specifiers, like %d for integers, %f for floats, and %s for strings, to determine how to display values and match them with the corresponding parameters.

Example:

Cpp

Output:

How to Format Output Using printf in C

Explanation: This program displays a name, age, and score via the printf() function to control formatting options, such as the precision of decimals, zero-padding values, and left alignment. It demonstrates how to lay out output from strings, integers, and floats using format specifiers.

Example Using Flags in printf() in C++

Here is an example that shows how the common flags in printf() affect the output formatting in C++:

Cpp

Output:

Example Using Flags in printf C

Explanation:

  • This program shows how each of the printf() flags can affect the output formatting options provided in C++.
  • Upon executing the program, it will print the integer num using the flags defined by the programmer, such as + (to show the plus sign), 0 (zero-padding), – (to left-align), and space (to add a leading space for positive numbers).
  • In addition to the above flags, it also demonstrates the # flag, which adds prefix characters such as 0x for hexadecimal output, as well as a decimal point when outputting floating point numbers.
  • The shown examples exhibit how each flag controls alignment, padding, sign, and prefixes to adjust console output and its clarity and thematic flexibility.

printf() vs cout() Performance Comparison in C++

Aspect printf() cout
Speed Usually faster Usually a bit slower
Safety No type checking; easy to misuse Type-safe; compiler checks types
Formatting Uses % specifiers; compact syntax Uses stream manipulators; longer
Ease of Use Simple for basic output Easier for complex or modern C++
Compatibility Great with old C code Designed for C++

Common Mistakes When Using printf() in C++

  • Using the wrong format specifier can make your output incorrect, or worse, garbage.
  • Having too few or too many arguments compared to the number of format specifiers in your format string will produce undefined behavior.
  • Forgetting to add \n for a newline, which will group outputs together and make reading harder
  • Using invalid or conflicting flags and widths may give you unexpected results.
  • Using sprintf() with no regard to buffer sizes, which can lead to buffer overflows; use snprintf() instead.
  • Forgetting to include the <cstdio> header can give you compiler errors.
  • Assuming the C++ printf function will format text the same way in every locale, this can produce inconsistencies.

Best Practices for Using printf() Safely in C++

  • Make sure to match format specifiers to the corresponding argument type and number of arguments. 
  • Use snprintf() and not sprintf() when writing to strings to avoid buffer overflow. 
  • Make sure to include the required header file. 
  • Make sure your format strings do not have typos or flags that are not valid. 
  • Always include a \n in outputs for your console logs to be clear and readable. 
  • Prefer using cout or modern C++ streams over printf() for type safety and interaction with C++ features. 
  • Be aware of locale differences if numbers or text being printed will be different across systems.

Conclusion

The C++ printf function is used to print output and comes from the C language. It is good for printing the formatted text, like numbers, names, and tables. It is still used because it is fast and gives control over how things look. But it also has some disadvantages, like not checking the type and not working well with modern C++ features. For simple or modern programs, cout is often easier to use.
If you’re getting ready, go through these C++ interview questions.

C++ Printf Function – FAQs

Q1. What is the print function in C++?

It is a way to show output on the screen, like printf() or cout.

Q2. What are %s and %d in C++?

%s is used to print a string, and %d is used to print an integer using printf in C++.

Q3. What is scanf in C++?

scanf is used to take input from the user in C or C++.

Q4. What is cout in C++?

cout is a C++ command to print output on the screen.

Q5. How to use a pointer in C++?

Use * to create a pointer and & to get the address of a variable, like int *ptr = &x;.

Q6. What is the difference between printf and cout in C++?

printf in C++ is a C-style formatted output function, while cout is the C++ stream-based output object.

Q7. Why is printf preferred in competitive programming?

printf is often faster and more concise for simple output in time-critical competitive programming.

Q8. How does sprintf differ from printf in C++?

sprintf writes formatted output to a string buffer, while printf writes it directly to the console.

Q9. Is printf faster than cout in C++?

Yes, printf is usually faster than cout because it has less overhead.

Q10. Which header file is used for printf in C++?

The printf function is declared in the or header.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner