• C Programming Video Tutorials

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.

Advertisements