Home >Backend Development >C++ >How to use printf in c++
The printf() function is used in C and C to format output data to standard output. It outputs different types of data to the screen in a specified format by using format specifiers (%d, %u, %f, %c, %s). Function syntax: printf(const char *format, ...), where format specifies the format and ... represents a variable number of parameters. It returns the number of characters printed or a negative value on error.
Usage of printf() in C
printf() is a standard library function in C and C. Use For formatting output data to standard output (usually the console). It allows developers to print different types of data to the screen in a controlled manner.
Usage:
The syntax of the printf() function is as follows:
<code class="cpp">int printf(const char *format, ...);</code>
Among them:
format
: A pointer to a format string that specifies how to format the output data. ...
: A variable number of arguments, corresponding to placeholders in the format string. Format options:
The format string uses format specifiers to specify how to output the data type. Common format specifiers include:
%d
: signed decimal integer %u
: unsigned decimal integer %f
: double precision floating point number %c
: character %s
: string Example:
The following code example shows how to use the printf() function to print different types of data:
<code class="cpp">#include <iostream> #include <cstdio> int main() { int age = 25; double gpa = 3.75; char grade = 'A'; std::string name = "John Smith"; // 打印不同类型的数据 printf("Name: %s\n", name.c_str()); printf("Age: %d\n", age); printf("GPA: %.2f\n", gpa); printf("Grade: %c\n", grade); return 0; }</code>
Output:
<code>Name: John Smith Age: 25 GPA: 3.75 Grade: A</code>
Note:
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!