c++-printf-function

“`html

The printf() function in C++ is utilized for displaying messages or values on the monitor. It originates from the C language but is also applicable in C++. You can employ it to exhibit numbers, strings, and characters in an organized manner. It employs format specifiers such as %d for integers and %s for strings. In this article, you will discover how printf() operates with straightforward examples and advice.

In this exposition, we will examine the printf() function in C++ thoroughly.

Table of Contents:

What is printf() in C++?

printf() is a function designed to output text to the console. It is derived from the C language and is also accessible in C++ via the <cstdio> or <stdio.h> header file.

Syntax of printf:

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

printf() Parameters

1. format: 

This is a string that includes the text to display, along with format specifiers for variables. It indicates which text to output. Its type is const char*.

Note: This argument is mandatory.

Example:

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

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

2. … (variable arguments)

This signifies a flexible number of additional arguments, often referred to as variadic arguments. These variables correspond one-for-one with the format specifiers. Furthermore, each argument type must align with the format specifier. 

Example:

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

In the previous illustration, 

  • 10 matches with %d
  • 3.14 matches with %.2f
  • ‘A’ matches with %c

Example:

Cpp

Code Copied!

var isMobile = window.innerWidth “);

editor50158.setValue(decodedContent); editor50158.clearSelection();

editor50158.setOptions({ maxLines: Infinity });

function decodeHTML50158(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

function copyCodeToClipboard50158() { const code = editor50158.getValue(); navigator.clipboard.writeText(code).then(() => { jQuery(“.maineditor50158 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor50158 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode50158() { var code = editor50158.getSession().getValue();

jQuery(“#runBtn50158 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “cpp”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output50158”).html(“

"+data+"");
        jQuery(".maineditor50158 .code-editor-output").show();
        jQuery("#runBtn50158 i.run-code").hide();
        
    }
})

}

function closeoutput50158() {	
var code = editor50158.getSession().getValue();
jQuery(".maineditor50158 .code-editor-output").hide();
}

// Event listeners for the buttons
document.getElementById("copyBtn50158").addEventListener("click", copyCodeToClipboard50158);
document.getElementById("runBtn50158").addEventListener("click", runCode50158);
document.getElementById("closeoutputBtn50158").addEventListener("click", closeoutput50158);


Output:

``````html
printf() Parameters

Description:

In the preceding illustration,

  • %s is substituted with the string “Ali”.
  • %d is substituted with the integer 25.
  • n introduces a newline at the conclusion.

printf() Return Result

The printf() function produces an integer. It reflects the total count of characters that have been printed effectively. Conversely, if a fault occurs, it yields a negative value.

Illustration:

Cpp
Code Copied!

Result:

printf() Return Value

Description:

In this illustration,

  • “Hello” consists of 5 characters
  • “,” consists of 1 character
  • the space consists of 1 character
  • “World” consists of 5 characters
  • “!” consists of 1 character
  • “n” consists of 1 character

Therefore, 5 + 1 + 1 + 5 + 1 + 1 = 14 characters

Note: printf() counts every character it displays, including spaces and n.

printf() Prototype

The prototype of the printf() function in C++ is defined in the <cstdio> library.

Syntax:

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

As illustrated above,

  • int is the return type of the function. It also indicates how many characters were printed.
  • printf is the designation of the function. It is included in the C standard library, stdio.h in C or in cstdio in C++.
  • . . . (ellipsis) indicates that the function can accept a variable number of arguments, which are the values that substitute the format specifiers in the format string. Each argument must correspond to the type of its respective format specifier.

Format Specifier

A format specifier is a code that initiates with % and directs printf() concerning the type of value desired for output, such as an integer, floating-point number, or a string.

There are numerous elements of a format specifier. These include:

1. Percent sign (%): This marks the commencement of the format specifier

2. Flags: These are special symbols that alter the presentation of the output, for instance, -, +, or 0.

3. Width: This defines the minimum space that the value should occupy

4. Precision: It determines how many decimal places to display for numbers or how many characters to print for strings.

5. Length modifier: It specifies the size of the data, such as short or long.

6. Conversion character: This is the key component that denotes the type of data, like %d for integers, %f for floats, or %s for strings.

Note: Except for % and the conversion character, the others are optional.

Flags

Flags are the additional symbols that can be included following the % sign in the format specifier. They... ``````html

Primarily alter the appearance of the output, i.e., its visual representation

Let us examine some frequently used flags in C++.

1. – (minus sign):
It aligns the output to the left within the specified space.

2. + (plus sign):
It consistently displays the sign, i.e., + or – before the numbers.

3. 0 (zero):
It populates extra spaces with zeros.

4. space:
If the number is positive, it leaves a space instead of a + sign.

5. # (hash):
It adds a prefix for certain types of numbers.

Example:

Cpp

Code Copied!

var isMobile = window.innerWidth ");

editor69441.setValue(decodedContent); // Set the initial text editor69441.clearSelection();

editor69441.setOptions({ maxLines: Infinity });

function decodeHTML69441(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard69441() { const code = editor69441.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor69441 .copymessage").show(); setTimeout(function() { jQuery(".maineditor69441 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode69441() { var code = editor69441.getSession().getValue(); jQuery("#runBtn69441 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output69441").html("

"+data+"");
            jQuery(".maineditor69441 .code-editor-output").show();
            jQuery("#runBtn69441 i.run-code").hide();
        }
    })
}
						
function closeoutput69441() {	
    jQuery(".maineditor69441 .code-editor-output").hide();
}

// Attach event listeners to the buttons
document.getElementById("copyBtn69441").addEventListener("click", copyCodeToClipboard69441);
document.getElementById("runBtn69441").addEventListener("click", runCode69441);
document.getElementById("closeoutputBtn69441").addEventListener("click", closeoutput69441);


Output:

Flags

The aforementioned code illustrates how format flags like +, 0, -, space, and # modify the output in printf().

Frequently Used Format Specifiers in C++

Here are some common format specifiers in C++:

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
%% Displays a percent sign % –

Note: Ensure to use the correct format specifier that corresponds to the data type you are outputting, otherwise, you will encounter incorrect results.

Parameter Values

The parameter values are the actual data provided to fulfill the format specifiers (%d, %s, etc.) in the format string.

There are specific rules regarding the parameter values in C++. These include:

1. Align the number: You must provide values for each format specifier such as %d, %s, etc. found in the format string.

2. Follow the order: The initial value should correspond to the first specifier, and the subsequent value should correspond to the next specifier.

3. Corresponding data type: Each value must be of the appropriate type for its specifier. For instance, %d requires an integer, while %s requires a string.

4. No omitted values: Avoid leaving any values out. If you fail to provide all necessary values, the printf() function will generate errors.

``````html

5. Refrain from providing: Do not supply more values than necessary, as any additional values will be disregarded.

C++ Printf versus Sprintf

1. printf()

This function displays formatted output on the console.

For instance:

Cpp
Code Copied!

"); jQuery(".maineditor15013 .code-editor-output").show(); jQuery("#runBtn15013 i.run-code").hide(); } }); }

function closeoutput15013() { jQuery(".maineditor15013 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn15013").addEventListener("click", copyCodeToClipboard15013); document.getElementById("runBtn15013").addEventListener("click", runCode15013); document.getElementById("closeoutputBtn15013").addEventListener("click", closeoutput15013);

Output:

printf

Clarification:

In the above code, printf first formats and outputs the message “You are 30 years old” directly without saving it to a separate variable beforehand.

2. Sprintf

This function produces formatted output to a string in memory. It emits the output as a character array in memory.

Note: Always opt for snprintf() instead of sprintf() to mitigate crashes and security vulnerabilities, as it constrains the number of characters written and prevents buffer overflows.

For instance:

Cpp

Code Copied!

var isMobile = window.innerWidth ");

editor89433.setValue(decodedContent); // Initialize the editor with preset text editor89433.clearSelection();

editor89433.setOptions({ maxLines: Infinity });

function decodeHTML89433(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard89433() { const code = editor89433.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor89433 .copymessage").show(); setTimeout(function() { jQuery(".maineditor89433 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode89433() { var code = editor89433.getSession().getValue();

jQuery("#runBtn89433 i.run-code").show(); // Code to run the C++ program goes here } ``````javascript i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output89433").html("

"+data+"");
        jQuery(".maineditor89433 .code-editor-output").show();
        jQuery("#runBtn89433 i.run-code").hide();
    }
})

}

function closeoutput89433() { var code = editor89433.getSession().getValue(); jQuery(".maineditor89433 .code-editor-output").hide(); }

// Add event listeners to the buttons document.getElementById("copyBtn89433").addEventListener("click", copyCodeToClipboard89433); document.getElementById("runBtn89433").addEventListener("click", runCode89433); document.getElementById("closeoutputBtn89433").addEventListener("click", closeoutput89433);

Result:

Sprintf

Clarification:

In the above script, the output is initially stored in a message, and subsequently displayed.

Both sprintf() and printf() yield the count of characters generated, not including the null terminator.

Feature printf() sprintf()
Intended Use Outputs formatted text to the console Saves formatted text to a character array (string in memory)
Output Destination Console / Standard output (stdout) Memory buffer (char[])
Includes Null Terminator No, it’s solely console output Yes, it appends a null terminator at the end of the string
Buffer Overflow Hazard No Yes, if the buffer size is insufficient
Application Scenario When formatted output needs to be displayed When formatted output needs to be stored in a string
Sample printf(“Age: %d”, 25); sprintf(buf, “Age: %d”, 25);

Why Opt for printf() Over cout in C++?

Although C++ provides the cout functionality, many opt for printf() due to the following reasons:

1. Heritage from C: Being an older function from C, those familiar with C may find it convenient to continue using printf() in C++.

2. Enhanced Formatting: printf() facilitates precise control over the appearance of the output.

3. Speed in Competitive Programming: printf() is generally quicker than cout, leading many programmers to prefer it during competitions.

4. Legacy Code: Older codebases, libraries, or projects often still utilize printf().

5. Effective for Tables and Clean Outputs: With printf(), it’s easier to generate neatly formatted tables or aligned values.

Drawbacks of printf() in C++

Regardless of its advantages, printf() has certain limitations:

1. printf() doesn't validate if the data type corresponds to the format specifier. For instance, using %d for a string by accident may lead to garbage output.

2. For lengthy or varied outputs, printf() can become convoluted and challenging to comprehend.

3. It employs fixed format specifiers (like %d, %s, %f), which can be restrictive.

4. Mistakes, such as incorrect specifiers for values, or forgetting the new line character (n), are common.

5. printf() does not integrate well with templates, namespaces, or streams such as files.

Final Thoughts

The printf() function is utilized to display output in C++ and originates from C. It is effective for printing formatted text, such as numbers, names, and tables. It remains popular due to its speed and the control it offers over the visible output. However, it has some disadvantages, including not verifying data types and its poor compatibility with modern C++ features. In simpler or more current applications, cout is frequently a more straightforward choice.

C++ Printf Function – Frequently Asked Questions

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

It is a method for displaying output on the screen, like printf() or cout.

Q2. What do %s and %d signify in C++?

%s is for printing a string, while %d is for printing an integer using printf().

Q3. What is scanf in C++?

scanf is employed to capture input from the user in C or C++.

Q4. What is cout in C++?

cout is a C++ command for printing output to the display.

Q5. How does one utilize a pointer in C++?

Use * to define a pointer and & to obtain a variable's address, like int *ptr = &x;.

The post C++ Printf Function appeared first on Intellipaat Blog.

```


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This