The printf() function in C++ 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() 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.
Syntax of printf:
#include <cstdio> // or #include <stdio.h>
int printf(const char *format, ...);
printf() Parameters
It is a string that contains the text to print, 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.
Example:
printf("Int: %d, Float: %.2f, Char: %cn", 10, 3.14, 'A');
In the above example,
- 10 corresponds to %d
- 3.14 corresponds to %.2f
- ‘A’ corresponds to %c
Example:
Output:
Explanation:
In the above example,
- %s is replaced by the string “Ali”.
- %d is replaced by the integer 25.
- n adds a newline at the end.
printf() Return Value
The 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:
Output:
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() counts all characters it prints, including spaces and n.
Get 100% Hike!
Master Most in Demand Skills Now!
printf() Prototype
The prototype of the printf() function in C++ 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.
A format specifier is a code that starts with % and tells printf() what type of value you want to print, like an integer, a float, or a string.
There are many components of a format specifier. These are as follows:
1. Percent sign (%): It is the starting 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, like 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++.
1. – (minus sign):
It left-aligns the output in the given space.
2. + (plus sign):
It always shows the sign, i.e., + or – in front of the numbers.
3. 0 (zero):
It fills the extra spaces with zeros.
4. space:
If the number is positive, leave a space instead of a + sign.
5. # (hash):
It adds a prefix for some number types.
Example:
Output:
The above code shows how format flags like +, 0, -, space, and # change the output in printf().
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) |
“Alice” |
%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 with the data type you are printing, else you will get the wrong output.
Parameter Values
The parameter values are the actual data that you provide to fill in the format specifiers (%d, %s, etc.) in the format string.
There are some rules for the parameter values in C++. These are as follows:
1. Match the number: You must give the values as there are format specifiers like %d, %s, etc. in the format string.
2. Match the order: the first value should go to the first specifier, and the second value should go to the second specifier.
3. 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.
4. No missing values: Do not leave out any values. If you do it, the printf() will print a garbage value
5. Avoid giving: Do not give more values than needed, as extra values will be ignored.
C++ Printf vs Sprintf
1. printf()
It prints the formatted output to the screen.
For example:
Output:
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:
Output:
Explanation:
In the above code, the message is first stored in the message, then it is printed.
Both sprintf() and printf() return the value of the total number of characters written, excluding the null terminator.
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 () |
No, it’s just console output |
Yes, it adds a 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); |
Why Use printf() Instead of cout in C++?
As C++ has the cout, many people still use printf() because of the following reasons:
1. 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.
2. It gives good formatting: printf() makes it easy to control how the output will look like.
3. Faster in Competitive Coding: printf() is usually faster than cout, so many coders use it in competitions.
4. Some Old Code Uses It: Older projects, codes, or C libraries still use the printf().
5. Useful for Tables and Clean Output: printf() is more controlled as it prints neat tables or aligned numbers.
Limitations of printf() in C++
Despite its advantages, printf() also has some limitations. They are:
1. printf() 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
2. For long or mixed outputs, printf() can get messy and hard to understand.
3. printf() uses fixed format specifiers (like %d, %s, %f) which are limiting.
4. It is easy to make mistakes like, wrong specifier for a value and forgetting n.
5. printf() does not work good with templates, namespaces, or streams like files.
Conclusion
The printf() function is used to print output in C++ 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.
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().
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;.