Stdin and Stdout in C
×


Stdin and Stdout in C

54

In C programming, stdin and stdout play crucial roles in managing input and output operations, respectively, fostering effective communication between programs and users.

What is Stdin?

Stdin, short for Standard Input, represents the standard input stream typically connected to the keyboard.

It facilitates programs in reading user-provided data during runtime.

By default, stdin adopts line buffering, capturing input until the user confirms by pressing the Enter key.


What is Stdout?

Stdout, or Standard Output, refers to the standard output stream commonly linked to the console or terminal.

It enables programs to present information or results to users.

Similar to stdin, stdout operates with line buffering as the default behavior.


Reading Input from Stdin:

The scanf function serves as the primary tool for acquiring user input via stdin.

Its syntax follows:

scanf("format_specifier", &variable);

In this format, the format_specifier denotes the anticipated data type, while &variable indicates the memory location to store the input.

Writing Output to Stdout:

For output presentation via stdout, the printf function is indispensable.

Its syntax is as follows:

printf("format_specifier", variable) ;  

Here, the format_specifier defines the output format, and variable holds the value to be displayed.


Examples:

Example 1: Reading Input from Stdin

Consider a scenario where user-provided details like name, age, and favorite number are captured and echoed back:

//program for stdin in C
#include<stdio.h> 

int main() {
    char name[50];
    int age;
    int favoriteNumber;

    printf("Enter your name: ");
    scanf("%s", name);
    printf("Enter your age: ");
    scanf("%d", &age);
    printf("Enter your favorite number: ");
    scanf("%d", &favoriteNumber);

    printf("Name: %s\n", name);
    printf("Age: %d\n", age);
    printf("Favorite Number: %d\n", favoriteNumber);

    return 0;
}

Output:

Enter your name: SIYA
Enter your age: 22
Enter your favorite number: 12
Name: SIYA
Age: 22
Favorite Number: 12

Example 2: Writing Output to Stdout

Let's calculate the sum of two user-provided values and display the result:

// program for stdout in C
#include<stdio.h> 
int main() {
    int num1, num2, sum;

    printf("Enter the first number: ");
    scanf("%d", &num1);
    printf("Enter the second number: ");
    scanf("%d", &num2);

    sum = num1 + num2;

    printf("The sum is: %d\n", sum);

    return 0;
}

Output:

Enter the first number: 4
Enter the second number: 4
The sum is: 8


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments