Everything You Need to Know About the C++ Printf Function

C++ printf is a formatting function that is used to print a string to stdout. The basic idea to call printf in C++ is to provide a string of characters that need to be printed as it is in the program. The printf in C++ also contains a format specifier that is replaced by the actual value during execution.

The C++ Printf Prototype

The C++ printf prototype is:

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

The printf prototype is defined in the <cstdio> header file. When you use the printf() function, it prints the string pointed out by the format to the standard output stdout. The format can also contain some specifiers that start with a % and replace values of variables with the printf() function. To put it simply, they work as additional arguments to the printf() function.

The C++ Printf Parameters

The C++ prototype contains the following parameters:

  • const char: Any text to be printed on the console as is
  • format: A pointer to the string with the optional format specifier starting with the %d sign.

Return Value of Printf in C++

C++ printf returns:

  • The number of characters written if successful
  • A negative value, if failed

Stand Out From Your Peers this Appraisal Season

Start Learning With Our FREE CoursesEnroll Now
Stand Out From Your Peers this Appraisal Season

General Form of Format Specifier

The general form of a C++ printf format specifier is as below:

%[flags][width][.precision][length]specifier

In the above format:

  • %: This is the leading sign that denotes the beginning of the format specifier
  • Flags: An optional one or more values that modifies the conversion behavior. The available values are:
    • -: The result of printf function is by default right justified. This value left justifies the results
    • +: This will add a sign to the values of the result, even for the positive values
    • Space: If there is no sign attached to a value, this will attach a space to the beginning of the result
    • #: This leads to an alternative form of conversion being performed
    • 0: You use this flag for integers and floating-point numbers to pad the values with zeros instead of space
  • Width: An optional field that accepts * or an integer value to determine the minimum width field
  • Precision: An optional argument specifies precision by accepting a *, integer value, or nothing after a ‘.’ symbol
  • Length: An optional parameter that defines the size of the argument
  • Specifier: This field accepts a conversion format specifier

Format Specifiers Used in C++ Printf

Printf in C++ can accept the following format specifiers.

Specifier

Description

%

Prints the % sign

c

Writes a single character to stdout

s

Writes a string to stdout

d or i

Transforms a signed integer to a decimal representation

o

Displays an unsigned integer using an octal representation

x or X

Transforms an unsigned integer to a hexadecimal representation

u

Displays an unsigned integer using a decimal representation

f or F

Turns a floating-point number into a decimal representation

e or E

Transforms a floating-point number to a decimal exponent notation

a or A

Displays a floating-point number using a hexadecimal exponent

g or G

Displays a floating-point number using decimal or decimal exponent notation

n

Returns the number of characters written by far using this call function. It writes the result to the value pointed by the argument.

p

A pointer that points to the implementation-defined character sequence

Examples of C++ Printf() Function

Now that you know the fundamentals of C++ printf, look at some examples that will give you a better understanding of how the printf() function in C++ works.

Example 1

In this example, you will simply display the value of an integer using %d and write a string to stdout using the %s format specifiers.

#include <cstdio>

int main(){

    int i = 9;

    char name[] = "Simplilearn";

    printf("i = %d \n", i);

    printf("Welcome to %s \n", name);    

    return 0;

}

Output:

C_Plus_Plus_Printf_Function_1.

Example 2

In this example, you will use various format specifiers from the above table to define the conversion behavior and get the result in the desired format.

#include <cstdio>

int main(){

    char c = 'S';

    float x = 7.0, y = 9.0;

    double d = 6.548;

    int i = 50;

    printf("The float division is : %.3f / %.3f = %.3f \n", x,y,x/y);

    printf("The double value is : %.4f \n", d);

    printf("Setting the width of c : %*c \n",3,c);

    printf("The octal equivalent of %d is %o \n",i,i);

    printf("The hex equivalent of %d is %x \n",i,i);

    return 0;

}

Output:

C_Plus_Plus_Printf_Function_2

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

C++ Printf Vs. Sprintf

The Sprintf() function in C++ is almost similar to the printf() function with a single major difference. While the C++ printf writes to the standard output, the sprintf writes the output to a string buffer. The sprintf() function prototype is:

int sprintf(char * buffer, const char * format, ...);

In the above prototype, the parameters are:

  • Buffer: Pointer to a buffer where the results will be written
  • Format: Pointer to a null-terminated string written to the file stream

Example of C++ Stringf() Function

In the below example, you will write a string to a buffer using the sprintf function and output the formatted string. You will also display the total number of characters written to the buffer.

#include <cstdio>

#include <iostream>

using namespace std;

int main(){

    char buf[100];

    int return_Val;

    char my_name[] = "Simplilearn";

    char topic[] = "tutorials";

    return_Val = sprintf(buf, "Welcome to %s you can read various programming %s here!!", my_name, topic);

    cout << buf << endl;

    cout << "Total characters written are: " << return_Val << endl;

    return 0;

}

Output:

C_Plus_Plus_Printf_Function_3

Printf Vs. Cout in C++

The C++ printf() function is usually used in C programming but can also run in C++. However, the cout is specifically an addition in C++. The table below displays the significant differences between the C++ printf and cout.

C++ Printf

C++ Cout

Most usage

C language

C++ language

Object of

<cstdio> header file

<iostream> header file

Format specifier

Takes specifier

It does not take specifier

Return value

Returns the number of characters if successful and a negative value if unsuccessful

It does not return any value

Type safe

Not type safe in input parameters

Type safe in input parameters

Example of C++ Cout

In the example below, you will see the use of C++ printf and cout simultaneously to see the difference.

#include <iostream>

using namespace std;

int main() {

   char c = 'S';

   cout<< "The value of c : " << c;

   printf("\nThe value of c : %c", c);  

   return 0;

}

Output:

C_Plus_Plus_Printf_Function_4.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

In this article, you learned everything about the C++ printf() function. You have also seen different format specifiers that you can use to format the results and used them in examples. Now it's time to use the other specifiers too. If you want to learn about more such fundamental concepts of C++ programming, you can refer to Simplilearn’s C++ Tutorial for Beginners. The tutorial is designed for beginners and covers all the basic concepts in detail. 

You can also take our SkillUp courses to sharpen your C++ and other programming language skills. If you are looking to pursue a career in web development, our Full-Stack Web Development Course might suit you. The course offers hours of applied learning and online learning materials to help you grasp multiple web development programming languages that can help you excel in the field.

Have any questions for us? Mention them as comments, and our experts will get back to you on the same, ASAP!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.