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

How to use printf in c++

下次还敢
下次还敢Original
2024-04-28 18:51:15630browse

In C, you can use the printf function to output formatted data, but it is recommended to use the cout object in the iostream library. The syntax is printf(const char *format, ...), where format specifies the format, and ... is a variable parameter list containing the data to be output. Format specifiers (such as %d, %f, %s) control the output format.

How to use printf in c++

Use of printf in C

printf is a function in the C language library, used to convert the format The transformed data is output to standard output (usually the console). In C, you can also use the printf function, but it is more recommended to use the iostream object provided by the C iostream library, such as cout.

Syntax

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

Among them:

  • format: A format string that specifies the format of the output data.
  • ...: Variable parameter list containing the data to be output.

Format specifier

Format specifiers can be used in the format string to control the format of the output data. Some commonly used format specifiers include:

  • %d: signed decimal integer
  • %u: unsigned decimal integer
  • %f: floating point number
  • %s: string
  • %c: character

Usage example

<code class="cpp">#include <cstdio>

int main() {
  int age = 25;
  float salary = 10000.50;
  char name[] = "John Doe";

  printf("年龄:%d\n", age);
  printf("工资:%.2f\n", salary);
  printf("姓名:%s\n", name);

  return 0;
}</code>
Output:

<code>年龄:25
工资:10000.50
姓名:John Doe</code>

Note:

    printf function does not check Error in formatting strings, so use with caution.
  • The iostream library is safer and easier to use, so it is recommended to use cout and cerr objects for output.

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:
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
Previous article:How to use scanf in c++Next article:How to use scanf in c++