Formatted Input Output in C

Learn how to use formatted input and output in C with printf and scanf. This tutorial explains format specifiers and how they help in displaying and receiving data properly in C programs on Debian 12 using Vim.

Formatted Input and Output in C

Formatted input and output allow you to control how data is displayed or received in C. The printf() function is used to display formatted output, while scanf() is used to read formatted input from the user.

What Are Format Specifiers?

Format specifiers define how different types of data are handled in printf and scanf. They act as placeholders for variables.

  • %d: Integer
  • %f: Floating-point number
  • %c: Single character
  • %s: String

Example Code Using printf and scanf

This example demonstrates reading and displaying an integer, float, character, and string using formatted input and output.

#include 

int main() 
    int age;
    float height;
    char grade;
    char name[50];

    printf(\\"Enter your name: \\");
    scanf(\\"%s\\", name);

    printf(\\"Enter your age: \\");
    scanf(\\"%d\\", &age);

    printf(\\"Enter your height in meters: \\");
    scanf(\\"%f\\", &height);

    printf(\\"Enter your grade: \\");
    scanf(\\" %c\\", &grade);

    printf(\\"Name: %s\\\
\\", name);
    printf(\\"Age: %d\\\
\\", age);
    printf(\\"Height: %.2f meters\\\
\\", height);
    printf(\\"Grade: %c\\\
\\", grade);

    return 0;

Key Concepts

  • %s: Reads a string. It stops at spaces, so no full names with spaces.
  • scanf(\\" %c\\", &grade): The space before %c skips whitespace left by earlier inputs.
  • %.2f: Limits the float to 2 decimal places in output.

Compiling and Running the Program

gcc format.c -o format
./format

Expected Output

Enter your name: Bob
Enter your age: 22
Enter your height in meters: 1.75
Enter your grade: A
Name: Bob
Age: 22
Height: 1.75 meters
Grade: A

Conclusion

Formatted input and output are powerful tools for interacting with users and displaying clean data in C. Learning format specifiers and their behavior is essential to write professional and readable code.

Subscribe to Our YouTube for More

Download as PDF

https://blog.arashtad.com/updates/formatted-input-output-in-c/?feed_id=13551&_unique_id=689e11d42acc5

Comments

Popular posts from this blog

Why Smart Contracts Are Revolutionary? (Smart Contracts Use Cases)

A Quick Guide to Tron Network Interaction using Python.

#36 Multi-Signature Wallet Smart Contract (Part 3)