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

How to use printf in c++

下次还敢
Release: 2024-04-28 18:51:15
Original
724 people have browsed it

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>
Copy after login
Output:

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

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!

Related labels:
c++
source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template