Table of contents
1.
Introduction
2.
What is Stdin? 
3.
What is Stdout?
4.
Reading Input from Stdin
5.
Writing Output to Stdout
6.
Unformatted Character Input & Output Functions: getchar() and putchar()
7.
Formatted String Input & Output Functions: gets(), fgets(), puts(), and fputs()
7.1.
For reading strings from stdin, you have two options: gets() and fgets(). 
7.2.
For writing strings to stdout, you have puts() and fputs().
8.
Formatted Input & Output Functions: scanf() and printf()
9.
Format Specifiers in C
10.
Frequently Asked Questions 
10.1.
What is the difference between stdin and stdout?
10.2.
What happens if I use gets() instead of fgets() to read a string from stdin?
10.3.
How do I specify the format of input or output when using scanf() or printf()?
11.
Conclusion
Last Updated: Dec 3, 2024
Easy

stdin and stdout in C

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In programming, interacting with data is a very important skill. Whether you're building a simple calculator or a complex data analysis tool, you need a way to take in user input and display output. In C language, stdin and stdout are two main concepts that allow you to do just that. Stdin stands for "standard input" & is used to read data from the user or other input sources. Stdout stands for "standard output" & is used to display data to the user or send output to other destinations. 

stdin and stdout in C

In this article, we'll discuss stdin & stdout in depth, and learn how to use them effectively in C programs.

What is Stdin? 

Stdin, short for standard input, is a way for C programs to read input data from the user or other sources. It's like a stream of characters that flows into your program. By default, stdin is connected to the keyboard. So when your program reads from stdin, it's usually waiting for the user to type something on the keyboard & press enter. 


But stdin isn't limited to keyboard input. You can redirect stdin to read from a file or even from the output of another program. That's what makes it so flexible & powerful. When you read from stdin in your C code, the program will wait until it receives some input before continuing. This allows for interactive programs that respond to user actions.

What is Stdout?

Stdout, which stands for standard output, is the counterpart to stdin. While stdin is used for reading input, stdout is used for writing output. By default, stdout is connected to the console or terminal window where your C program is running. So when you write to stdout, the output will appear on the screen for the user to see.


Just like with stdin, stdout can be redirected. Instead of sending output to the screen, you can write to a file or pipe the output to another program. This is handy for saving results, logging, or chaining multiple programs together.

C provides several functions for writing to stdout, such as putchar(), puts(), fputs() & printf(). These functions allow you to output characters, strings & formatted data. We'll discuss them in detail in the coming sections.

One important thing to note about stdout is that it's buffered. This means that output written to stdout may not appear immediately on the screen. Instead, it's stored in a buffer until a newline character is encountered or the buffer becomes full. You can force the buffer to be emptied & the output to be displayed immediately by calling the fflush() function.

Reading Input from Stdin

Now that we know what stdin is, let's see how to read input from it in C. There are a few different functions you can use, depending on your needs.

The most basic function for reading from stdin is getchar(). It reads a single character from stdin & returns it as an int value. 

For example:

#include <stdio.h>

int main() {
    int ch;
    printf("Enter a character: ");
    ch = getchar();
    printf("You entered: %c\n", ch);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


In this code, getchar() reads one character from stdin. The program waits until the user types a character & presses enter. The character is then stored in the ch variable & printed back to the user using printf().

If you want to read a whole string from stdin, you can use the gets() function. It reads characters from stdin until a newline is encountered & stores them in a string. 

For example:

#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    gets(str);
    printf("You entered: %s\n", str);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


The gets() function reads characters from stdin & stores them in the str array until the user presses enter. The string is then printed back using printf().

However, gets() is considered dangerous because it doesn't check for buffer overflow. If the user enters more characters than the str array can hold, it will cause undefined behavior. A safer alternative is fgets(), which allows you to specify the maximum number of characters to read:

#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, 100, stdin);
    printf("You entered: %s", str);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


fgets() reads up to 99 characters (plus a null terminator) from stdin & stores them in str. If the user enters more than 99 characters, the rest are discarded.

Finally, scanf() is a powerful function for reading formatted input from stdin. It allows you to specify a format string that describes the expected input, & it will parse the input accordingly. 

For example:

#include <stdio.h>

int main() {
    int age;
    char name[50];
    printf("Enter your age & name: ");
    scanf("%d %s", &age, name);
    printf("You entered: Age = %d, Name = %s\n", age, name);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


In this code, scanf() expects an integer followed by a string. It reads the input from stdin, parses it according to the format string, & stores the results in the age & name variables.

Writing Output to Stdout

Just as there are several functions for reading from stdin, there are also multiple ways to write output to stdout in C.

The simplest function for writing to stdout is putchar(). It takes a single character as an argument & writes it to stdout. For example:

#include <stdio.h>
int main() {
    char ch = 'A';
    putchar(ch);
    putchar('\n');
    return 0;
}
You can also try this code with Online C Compiler
Run Code


This code writes the character 'A' to stdout, followed by a newline character '\n'. The output will be:

A


If you want to write a string to stdout, you can use the puts() function. It takes a string as an argument, writes it to stdout, & automatically appends a newline character at the end. Here's an example:

#include <stdio.h>
int main() {
    char str[] = "Hello, world!";
    puts(str);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


The output will be:

Hello, world!


Another function for writing strings to stdout is fputs(). It's similar to puts(), but it doesn't append a newline character automatically. You have to add it manually if you want a new line. For example:

#include <stdio.h>

int main() {
    char str[] = "Hello, world!";
    fputs(str, stdout);
    fputs("\n", stdout);
    return 0;
}
You can also try this code with Online C Compiler
Run Code

This code writes "Hello, world!" to stdout, followed by a newline character.

Finally, printf() is the most versatile function for writing formatted output to stdout. It allows you to specify a format string that describes how the output should be structured, & it can print variables of different types. 

For example:

#include <stdio.h>

int main() {
    int age = 25;
    char name[] = "Rahul";
    printf("My name is %s & I am %d years old.\n", name, age);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


The output will be:

My name is Rahul & I am 25 years old.


The format string in printf() contains placeholders like %s & %d, which are replaced by the values of the corresponding variables.

Unformatted Character Input & Output Functions: getchar() and putchar()

Let's take a closer look at the unformatted character I/O functions in C: getchar() and putchar().

getchar() is used to read a single character from stdin. It reads the next available character from the input stream and returns it as an int value. If there are no characters available, getchar() will wait until one is entered. For example:

#include <stdio.h>
int main() {
    int ch;
    printf("Enter a character: ");
    ch = getchar();
    printf("You entered: %c\n", ch);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


In this code, getchar() reads a single character from stdin and stores it in the ch variable. The character is then printed back to the user using printf().

One thing to note is that getchar() will read all characters from stdin, including newline characters. So if you want to read multiple characters, you may need to consume the newline character separately.

On the flip side, putchar() is used to write a single character to stdout. It takes an int value representing a character and writes it to the output stream. For example:

#include <stdio.h>
int main() {
    char ch = 'A';
    putchar(ch);
    putchar('\n');
    return 0;
}
You can also try this code with Online C Compiler
Run Code


This code writes the character 'A' to stdout, followed by a newline character '\n'.

getchar() and putchar() are the most basic unformatted I/O functions in C. They're useful for reading and writing individual characters, but not as convenient for handling strings or formatted data.

Note: One advantage of using getchar() and putchar() is that they're very efficient. They don't have the overhead of parsing format strings like scanf() and printf() do. So if you just need to read or write a single character, they can be a good choice.

Formatted String Input & Output Functions: gets(), fgets(), puts(), and fputs()

In addition to reading and writing individual characters with getchar() and putchar(), C also provides functions for handling strings. These functions allow you to read and write entire strings at once, which can be more convenient than processing characters one at a time.

For reading strings from stdin, you have two options: gets() and fgets(). 

gets() reads characters from stdin until a newline character is encountered, and then stores the string in a character array. For example:

#include <stdio.h>
int main() {
    char str[100];
    printf("Enter a string: ");
    gets(str);
    printf("You entered: %s\n", str);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


However, gets() is considered dangerous because it doesn't perform any bounds checking. If the user enters more characters than the array can hold, it will cause buffer overflow and lead to undefined behavior. For this reason, gets() has been removed from the latest C standard (C11) and should be avoided.

A safer alternative is fgets(), which allows you to specify the maximum number of characters to read. For example:

#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    printf("You entered: %s\n", str);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


fgets() reads up to one less than the specified number of characters from stdin and stores them in the string. It stops reading when a newline character is encountered or when the maximum count is reached. The newline character is included in the stored string, so you may need to remove it manually if needed.

For writing strings to stdout, you have puts() and fputs().

puts() writes a string to stdout and automatically appends a newline character at the end. For  example:

#include <stdio.h>

int main() {
    char str[] = "Hello, world!";
    puts(str);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


This will output:

Hello, world!


fputs() is similar to puts(), but it doesn't append a newline character automatically. You have to add it manually if you want a newline. For example:

#include <stdio.h>
int main() {
    char str[] = "Hello, world!";
    fputs(str, stdout);
    fputs("\n", stdout);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


This will produce the same output as the previous example.

Note: gets(), fgets(), puts(), and fputs() provide a convenient way to read and write strings in C. They handle the memory management for you and make it easy to work with string data.

Formatted Input & Output Functions: scanf() and printf()

scanf() and printf() are powerful functions for reading and writing formatted data in C. They allow you to specify format strings that describe the structure of the input or output, and they handle the parsing and conversion of different data types.

scanf() is used for reading formatted input from stdin. It reads input according to a format string and stores the results in corresponding variables. For example:

#include <stdio.h>

int main() {
    int age;
    char name[50];
    printf("Enter your age and name: ");
    scanf("%d %s", &age, name);
    printf("You entered: Age = %d, Name = %s\n", age, name);
    return 0;
}
You can also try this code with Online C Compiler
Run Code

 

In this code, scanf() expects an integer followed by a string, separated by whitespace. It reads the input from stdin, parses it according to the format string, and stores the results in the age and name variables.

The format string in scanf() contains format specifiers like %d and %s, which match the input data types. %d is for integers, %s is for strings, %f is for floating-point numbers, and so on. The variables that will store the input values are passed as arguments to scanf() in the same order as the format specifiers.

printf() is the counterpart to scanf() and is used for writing formatted output to stdout. It takes a format string and a list of arguments, and it writes the output according to the specified format. Here's an example:

#include <stdio.h>

int main() {
    int age = 25;
    char name[] = "Rahul";
    printf("My name is %s and I am %d years old.\n", name, age);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


The output will be:

My name is Rahul and I am 25 years old.


The format string in printf() contains placeholders like %s and %d, which are replaced by the values of the corresponding arguments. The arguments are passed to printf() in the same order as the format specifiers.

scanf() and printf() provide a lot of flexibility and control over input and output formatting. They support various format specifiers for different data types, field widths, precision, and more.

However, it's important to use these functions carefully. If the format string doesn't match the actual input or output, it can lead to undefined behavior. It's also a good practice to check the return value of scanf() to ensure that the input was successfully parsed.

Format Specifiers in C

Format specifiers are used in scanf() and printf() to specify the type and format of the input or output data. They are placeholders in the format string that tell the functions how to interpret the corresponding arguments. Let’s look at some commonly used format specifiers in C:

1. %d or %i: Used for reading or writing signed integers (int).

Example: scanf("%d", &num); or printf("Number: %d\n", num);
 

2. %u: Used for reading or writing unsigned integers (unsigned int).

Example: scanf("%u", &num); or printf("Number: %u\n", num);
 

3. %f: Used for reading or writing floating-point numbers (float).

Example: scanf("%f", &num); or printf("Number: %f\n", num);
 

4. %lf: Used for reading or writing double-precision floating-point numbers (double).

Example: scanf("%lf", &num); or printf("Number: %lf\n", num);
 

5. %c: Used for reading or writing single characters (char).

Example: scanf(" %c", &ch); or printf("Character: %c\n", ch);
 

6. %s: Used for reading or writing strings (char array).

Example: scanf("%s", str); or printf("String: %s\n", str);
 

7. %p: Used for reading or writing pointers (void*).

Example: scanf("%p", &ptr); or printf("Pointer: %p\n", ptr);


These are just a few examples of format specifiers. There are more specifiers available for different data types and formatting options. You can also use modifiers like field width, precision, and justification to further customize the input or output.

For example: 

#include <stdio.h>
int main() {
    int num;
    float fnum;
    char ch;
    char str[20];
    printf("Enter an integer, a float, a character, and a string: ");
    scanf("%d %f %c %s", &num, &fnum, &ch, str);
    printf("Integer: %d\n", num);
    printf("Float: %f\n", fnum);
    printf("Character: %c\n", ch);
    printf("String: %s\n", str);


    return 0;
}
You can also try this code with Online C Compiler
Run Code


In this code, scanf() reads an integer, a float, a character, and a string from stdin using the appropriate format specifiers. The input values are then printed back to stdout using printf() and the corresponding format specifiers.

Frequently Asked Questions 

What is the difference between stdin and stdout?

Stdin is used for reading input, while stdout is used for writing output. Stdin is typically connected to the keyboard, and stdout is connected to the console or terminal window.

What happens if I use gets() instead of fgets() to read a string from stdin?

Using gets() is dangerous because it doesn't perform any bounds checking. If the input exceeds the size of the allocated buffer, it can cause buffer overflow and lead to undefined behavior. It's safer to use fgets() instead.

How do I specify the format of input or output when using scanf() or printf()?

You use format specifiers in the format string to specify the type and format of the input or output. Format specifiers start with a % symbol followed by a character indicating the data type, such as %d for integers or %s for strings.

Conclusion

In this article, we discussed the concepts of stdin and stdout in C language. We learned how to read input from stdin using functions like getchar(), fgets(), and scanf(), and how to write output to stdout using putchar(), puts(), fputs(), and printf(). We also discussed the importance of using format specifiers to control the input and output formatting. With these tools, you can create interactive programs that communicate with the user through the console.

You can also check out our other blogs on Code360.

Live masterclass