What is the usage of printf in C++?

In C++, printf() is an output function used to print formatted strings and the values of other variables to standard output or a file. Its basic syntax is as follows:

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

Here, the format is a character array or string constant that specifies the output format, while… represents a variable list of parameters. The data type and format of the output can be specified by formatting specifiers.

Here are some commonly used formatting specifiers:

  1. %d: Used for printing integers.
  2. %f: used for printing floating point numbers.
  3. %c: used for printing characters.
  4. %s: used for printing a string.
  5. %p: Used to print the address of a pointer.
  6. %x or %X: used to print hexadecimal numbers.
  7. “%o: Used for printing octal numbers.”

For example, the following code will output an integer and a string:

int num = 10;
char str[] = "Hello";
printf("Number: %d\n", num);
printf("String: %s\n", str);

The output will be:

Number: 10
String: Hello

You can also use multiple formatting specifiers to print the values of multiple variables in order. For example:

int a = 10;
float b = 3.14;
char c = 'A';
printf("a = %d, b = %f, c = %c\n", a, b, c);

The output will be:

a = 10, b = 3.140000, c = A

Please note that the printf() function returns the number of characters printed, and a negative value if an error occurs.

bannerAds