C++ Format Specifiers
Format specifiers define the type of data to be read or displayed using printf and scanf in C++. They allow precise control over input/output formatting.
1. Common Format Specifiers
| Specifier | Data Type | Example |
|---|---|---|
| %d | int (decimal) | printf("%d", 100); |
| %i | int (decimal) | printf("%i", 200); |
| %f | float | printf("%f", 3.14); |
| %lf | double | printf("%lf", 3.141592); |
| %c | char | printf("%c", 'A'); |
| %s | string/char array | printf("%s", "Hello"); |
| %x | hexadecimal | printf("%x", 255); |
| %o | octal | printf("%o", 10); |
| %p | pointer address | printf("%p", ptr); |
2. Using printf
The printf function prints formatted output to the console. It uses format specifiers to indicate the type and format of the values.
C++
Example using printf
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int a = 10;
float b = 3.14;
char c = 'A';
char str[] = "CodeCrown";
printf("Integer: %d\n", a);
printf("Float: %.2f\n", b); // 2 decimal places
printf("Character: %c\n", c);
printf("String: %s\n", str);
return 0;
}
3. Using scanf
The scanf function reads input from the user according to format specifiers. Ensure that the variable type matches the specifier.
C++
Example using scanf
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int age;
float height;
char name[50];
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your height: ");
scanf("%f", &height);
printf("Enter your name: ");
scanf("%s", name);
printf("Name: %s, Age: %d, Height: %.2f\n", name, age, height);
return 0;
}
4. Formatting Options
- Specify width: printf("%5d", num); // Minimum 5 characters wide
- Precision: printf("%.2f", num); // 2 decimal places
- Left alignment: printf("%-5d", num);
- Leading zeros: printf("%05d", num);
5. Complete Example Program
C++
Program demonstrating various format specifiers
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int num = 255;
float pi = 3.14159;
char ch = 'C';
char str[] = "CodeCrown";
printf("Integer: %d\n", num);
printf("Hex: %x\n", num);
printf("Octal: %o\n", num);
printf("Float (2 decimals): %.2f\n", pi);
printf("Character: %c\n", ch);
printf("String: %s\n", str);
return 0;
}
Conclusion
Format specifiers in C++ allow precise control over input and output. Using printf and scanf effectively ensures proper formatting and accurate reading of user input.
Codecrown