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

SpecifierData TypeExample
%dint (decimal)printf("%d", 100);
%iint (decimal)printf("%i", 200);
%ffloatprintf("%f", 3.14);
%lfdoubleprintf("%lf", 3.141592);
%ccharprintf("%c", 'A');
%sstring/char arrayprintf("%s", "Hello");
%xhexadecimalprintf("%x", 255);
%ooctalprintf("%o", 10);
%ppointer addressprintf("%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.