The printf() function is a C standard library function used to output formatted data to a terminal or file. It contains a format string that specifies the output format and allows passing a variable number of arguments to provide the actual data. Format strings use format specifiers to specify the format and alignment of data types. Common types include integers (%d), floats (%f), characters (%c), and strings (%s). printf() writes formatted output to the terminal or file based on a format string and supplied data, and returns the number of characters successfully output.
Usage of printf() function in C
What is printf() function?
printf() is a standard input and output library function in C, used to output formatted data to the terminal or file.
Syntax:
<code class="cpp">int printf(const char *format, ...);</code>
Among them:
format
: Format string, specify the format of the output content . ...
: A variable number of parameters that provide the data to be output in the order of the types specified in the format string. Format string:
The format string consists of the following elements:
%
, specify the format and alignment of the data type. Format specifier syntax:
<code>% [flags] [width] [.precision] type</code>
Among them:
Common format specifier types:
Data type | |
---|---|
%d
| Decimal integer|
%f
| Floating point number|
Character |
|
String |
<code class="cpp">#include <iostream>
using namespace std;
int main() {
int age = 25;
string name = "John";
// 输出一个格式化的字符串
printf("Name: %s, Age: %d\n", name.c_str(), age);
return 0;
}</code>
<code>Name: John, Age: 25</code>
The data type in the format string must match the provided parameters.
The above is the detailed content of How to use printf in c++. For more information, please follow other related articles on the PHP Chinese website!