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:
- %d: Used for printing integers.
- %f: used for printing floating point numbers.
- %c: used for printing characters.
- %s: used for printing a string.
- %p: Used to print the address of a pointer.
- %x or %X: used to print hexadecimal numbers.
- “%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.