In this guide, you will learn what is printf() function is in C++ programming and how to use it with an example.
1. printf() Function Overview
The printf() function is a part of the <cstdio> library in C++. It is used to print formatted data to the standard output. The function interprets the format string and formats the subsequent arguments accordingly, then outputs the resulting string.
Signature:
int printf(const char* format, ...);
Parameters:
- format: A string that contains text and format specifiers, which define the expected data types for the subsequent arguments.
- ...: Variable number of arguments to be formatted and printed according to the format string.
2. Source Code Example
#include <iostream>
#include <cstdio>
int main() {
int age = 25;
const char* name = "JohnDoe";
// Print formatted data to the standard output
printf("Name: %s\nAge: %d\n", name, age);
double pi = 3.14159;
printf("Value of Pi up to 3 decimal places: %.3f\n", pi);
return 0;
}
Output:
Name: JohnDoe Age: 25 Value of Pi up to 3 decimal places: 3.142
3. Explanation
1. We define an integer age and a string name.
2. The printf() function is then used to print these values in a formatted manner to the standard output. The %s format specifier is used for the string name, and the %d format specifier is used for the integer age.
3. We further use printf() to print the value of pi up to 3 decimal places. The format specifier %.3f indicates that the floating-point number should be printed with a precision of three decimal places.
Comments
Post a Comment