- C Programming Tutorial
- C - Home
- Basics of C
- C - Overview
- C - Features
- C - History
- C - Environment Setup
- C - Program Structure
- C - Hello World
- C - Compilation Process
- C - Comments
- C - Tokens
- C - Keywords
- C - Identifiers
- C - User Input
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Integer Promotions
- C - Type Conversion
- C - Type Casting
- C - Booleans
- Constants and Literals in C
- C - Constants
- C - Literals
- C - Escape sequences
- C - Format Specifiers
- Operators in C
- C - Operators
- C - Arithmetic Operators
- C - Relational Operators
- C - Logical Operators
- C - Bitwise Operators
- C - Assignment Operators
- C - Unary Operators
- C - Increment and Decrement Operators
- C - Ternary Operator
- C - sizeof Operator
- C - Operator Precedence
- C - Misc Operators
- Decision Making in C
- C - Decision Making
- C - if statement
- C - if...else statement
- C - nested if statements
- C - switch statement
- C - nested switch statements
- Loops in C
- C - Loops
- C - While loop
- C - For loop
- C - Do...while loop
- C - Nested loop
- C - Infinite loop
- C - Break Statement
- C - Continue Statement
- C - goto Statement
- Functions in C
- C - Functions
- C - Main Function
- C - Function call by Value
- C - Function call by reference
- C - Nested Functions
- C - Variadic Functions
- C - User-Defined Functions
- C - Callback Function
- C - Return Statement
- C - Recursion
- Scope Rules in C
- C - Scope Rules
- C - Static Variables
- C - Global Variables
- Arrays in C
- C - Arrays
- C - Properties of Array
- C - Multi-Dimensional Arrays
- C - Passing Arrays to Function
- C - Return Array from Function
- C - Variable Length Arrays
- Pointers in C
- C - Pointers
- C - Pointers and Arrays
- C - Applications of Pointers
- C - Pointer Arithmetics
- C - Array of Pointers
- C - Pointer to Pointer
- C - Passing Pointers to Functions
- C - Return Pointer from Functions
- C - Function Pointers
- C - Pointer to an Array
- C - Pointers to Structures
- C - Chain of Pointers
- C - Pointer vs Array
- C - Character Pointers and Functions
- C - NULL Pointer
- C - void Pointer
- C - Dangling Pointers
- C - Dereference Pointer
- C - Near, Far and Huge Pointers
- C - Initialization of Pointer Arrays
- C - Pointers vs. Multi-dimensional Arrays
- Strings in C
- C - Strings
- C - Array of Strings
- C - Special Characters
- C Structures and Unions
- C - Structures
- C - Structures and Functions
- C - Arrays of Structures
- C - Self-Referential Structures
- C - Lookup Tables
- C - Dot (.) Operator
- C - Enumeration (or enum)
- C - Structure Padding and Packing
- C - Nested Structures
- C - Anonymous Structure and Union
- C - Unions
- C - Bit Fields
- C - Typedef
- File Handling in C
- C - Input & Output
- C - File I/O (File Handling)
- C Preprocessors
- C - Preprocessors
- C - Pragmas
- C - Preprocessor Operators
- C - Macros
- C - Header Files
- Memory Management in C
- C - Memory Management
- C - Memory Address
- C - Storage Classes
- Miscellaneous Topics
- C - Error Handling
- C - Variable Arguments
- C - Command Execution
- C - Math Functions
- C - Static Keyword
- C - Random Number Generation
- C - Command Line Arguments
- C Programming Resources
- C - Questions & Answers
- C - Quick Guide
- C - Cheat Sheet
- C - Useful Resources
- C - Discussion
Input and Output Functions in C
Reading input from the user and showing it on the console (output) are the common tasks every C program needs. C language provides libraries (header files) that contain various functions for input and output. In this tutorial, we will learn different types of formatted and unformatted input and output functions.
The Standard Files in C
The C language treats all the devices as files. So, devices such as the "display" are addressed in the same way as "files".
The following three files are automatically opened when a program executes to provide access to the keyboard and screen.
Standard File | File | Device |
---|---|---|
Standard input | stdin | Keyboard |
Standard output | stdout | Screen |
Standard error | stderr | Your screen |
To access a file, C uses a predefined FILE struct type to refer to the file for reading and writing purpose. Read this chapter to understand how to read values from the screen and how to print the result on the screen.
Types of Input and Output Functions
We have the following categories of IO function in C −
- Unformatted character IO functions: getchar() and putchar()
- Unformatted string IO functions: gets() and puts()
- Formatted IO functions: scanf() and printf()
The unformatted I/O functions read and write data as a stream of bytes without any format, whereas formatted I/O functions use predefined formats like "%d", "%c" or "%s" to read and write data from a stream.
Unformatted Character Input & Output Functions: getchar() and putchar()
These two functions accept a single character as input from the keyboard, and display a single character on the output terminal, respectively.
The getchar() function it reads a single key stroke without the Enter key.
int getchar(void)
There are no parameters required. The function returns an integer corresponding to the ASCII value of the character key input by the user.
Example 1
The following program reads a single key into a char variable −
#include <stdio.h> int main() { char ch; printf("Enter a character: "); ch = getchar(); puts("You entered: "); putchar(ch); return 0; }
Output
Run the code and check its output −
Enter a character: W You entered: W
Example 2
The following program shows how you can read a series of characters till the user presses the Enter key −
#include <stdio.h> int main() { char ch; char word[10]; int i = 0; printf("Enter characters. End with pressing enter: "); while(1) { ch = getchar(); word[i] = ch; if (ch == '\n') break; i++; } printf("\nYou entered the word: %s", word); return 0; }
Output
Run the code and check its output −
Enter characters. End with pressing enter: Hello You entered the word: Hello
You can also use the unformatted putchar() function to print a single character. The C library function "int putchar(int char)" writes a character (an unsigned char) specified by the argument char to stdout.
int putchar(int c)
A single parameter to this function is the character to be written. You can also pass its ASCII equivalent integer. This function returns the character written as an unsigned char cast to an int or EOF on error.
Example 3
The following example shows how you can use the putchar() function −
#include <stdio.h> int main() { char ch; for(ch = 'A' ; ch <= 'Z' ; ch++) { putchar(ch); } return(0); }
Output
When you run this code, it will produce the following output −
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Formatted String Input & Output Functions: gets(), fgets(), puts(), and fputs()
The char *gets(char *str) function reads a line from stdin into the buffer pointed to by str until either a terminating newline or EOF (End of File) is encountered.
char *gets (char *str)
This function has a single argument. It is the pointer to an array of chars where the C string is stored. The function returns "str" on success and NULL on error or when EOF occurs while no characters have been read.
Example
Take a look at the following example −
#include <stdio.h> int main() { char name[20]; printf("Enter your name: "); gets(name); printf("You entered the name: %s", name); return 0; }
Output
Enter your name: Ravikant Soni You entered the name: Ravikant Soni
scanf("%s") reads characters until it encounters a whitespace (space, tab, newline, etc.) or EOF. So, if you try to input a string with multiple words (separated by a whitespace), then it accepts characters before the first whitespace as the input to string.
fgets() Function
In newer versions of C, gets() has been deprecated as it is potentially a dangerous function because it doesn’t perform bound checks and may result in buffer overflow.
Instead, it is advised to use fgets() function −
fgets(char arr[], size, stream);
fgets() can be used to accept input from any input stream such as stdin (keyboard) or FILE (file stream).
Example 1
The following program shows how you can use fgets() to accept multi-word input from the user −
#include <stdio.h> int main () { char name[20]; printf("Enter a name: \n"); fgets(name, sizeof(name), stdin); printf("You entered: \n"); printf("%s", name); return 0; }
Output
Run the code and check its output −
Enter a name: Rakesh Sharma You entered: Rakesh Sharma
The function "int puts (const char *str)" writes the string 's' and a trailing newline to stdout.
int puts(const char *str)
The str parameter is the C string to be written. If successful, it returns a non-negative value. On error, the function returns EOF.
We can use the printf() function with %s specifier to print a string. We can also use the puts() function (deprecated in C11 and C17 versions) or the fputs() function as an alternative.
Example 2
The following example shows the difference between puts() and fputs() −
#include <stdio.h> int main () { char name[20] = "Rakesh Sharma"; printf("With puts(): \n"); puts(name); printf("\nWith fputs(): \n"); fputs(name, stdout); return 0; }
Output
Run the code and check its output −
With puts(): Rakesh Sharma With fputs(): Rakesh Sharma
Formatted Input & Output Functions: scanf() and printf()
The scanf() function reads the input from the standard input stream stdin and scans that input according to the format provided −
int scanf(const char *format, ...)
The printf() function writes the output to the standard output stream stdout and produces the output according to the format provided.
int printf(const char *format, ...)
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings, integers, characters or floats respectively. There are many other formatting options available which can be used based on the specific requirements.
Format Specifiers in C
The CPU performs IO operations with input and output devices in a streaming manner. The data read from a standard input device (keyboard) through the standard input stream is called stdin. Similarly, the data sent to the standard output (computer display screen) through the standard output device is called stdout.
The computer receives data from the stream in a text form, however you may want to parse it in variables of different data types such as int, float or a string. Similarly, the data stored in int, float or char variables has to be sent to the output stream in a text format. The format specifier symbols are used exactly for this purpose.
ANSI C defines a number of format specifiers. The following table lists the different specifiers and their purpose.
Format Specifier | Type |
---|---|
%c | Character |
%d | Signed integer |
%e or %E | Scientific notation of floats |
%f | Float values |
%g or %G | Similar as %e or %E |
%hi | Signed integer (short) |
%hu | Unsigned Integer (short) |
%i | Unsigned integer |
%l or %ld or %li | Long |
%lf | Double |
%Lf | Long double |
%lu | Unsigned int or unsigned long |
%lli or %lld | Long long |
%llu | Unsigned long long |
%o | Octal representation |
%p | Pointer |
%s | String |
%u | Unsigned int |
%x or %X | Hexadecimal representation |
A minus sign (−) signifies left alignment. A number after "%" specifies the minimum field width. If a string is less than the width, it will be filled with spaces. A period (.) is used to separate field width and precision.
Example
The following example demonstrates the importance of format specifiers −
#include <stdio.h> int main(){ char str[100]; printf("Enter a value: "); gets(str); printf("\nYou entered: "); puts(str); return 0; }
Output
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press the Enter button, the program proceeds and reads the input and displays it as follows −
Enter a value: seven 7 You entered: seven 7
Here, it should be noted that the scanf() function expects the input in the same format as you provided "%s" and "%d", which means you have to provide valid inputs like "a string followed by an integer". If you provide two consecutive strings "string string" or two consecutive integers "integer integer", then it will be assumed as an incorrect set of input.
Secondly, while reading a string, the scanf() function stops reading as soon as it encounters a "space", so the string "This is Test" is actually a set of three strings for the scanf() function.