Home > Backend Development > C++ > How to use printf in c++

How to use printf in c++

下次还敢
Release: 2024-05-01 14:21:19
Original
1443 people have browsed it

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.

How to use printf in c++

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:

int printf(const char *format, ...);
Copy after login

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:

#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;
}
Copy after login

Output:

<code>Name: John Smith
Age: 25
GPA: 3.75
Grade: A</code>
Copy after login

Note:

  • The format specifier must match the data type of the corresponding parameter.
  • If the number of fields specified in the format string is less than the actual number of parameters, the extra parameters will be ignored.
  • The printf() function returns the number of characters printed, or a negative value if an error occurs.

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template