C Input & Output

Input & Output is the way general purpose computer can communicate or interact to the outside world. In C Programming Language input & output is the way program can read in or write out data streams,streams can be used for both unformatted and formatted input and output.To perform standard input and output, we need to include the following preprocessor directive into our files.

There are three standard streams are available to all c programs –

  • stdin (standard input)
  • stdout (standard output)
  • stderr (standard error)

Reading and writing single characters

getchar() function is used to read a single character from the “stdin” data stream, it returns the EOF (end of file) if there are no more characters to read or when you hit the end of a file or when the user types the end of file.

putchar() function is used to write a single character to the “stdout” data stream. It puts single character at a time, we can loop it for writing multiple characters.

Example:

Reading and writing string

The gets() function reads the input data stream until the EOF determined, while puts() function is used to write a string to “stdout” stream until new line character detected.

Syntax:

Example:

Formatted I/O

The printf() function

The printf() function is used for writing formatted out to the “stdout” stream. This way it allows us to print values and variables to the standard output stream (in most cases, the screen).

Syntax:

Example:

The above printf statement contains two sets of arguments: the control string enclosed in double quotes, and a identifiers to specify the value to be printed. The control string contains text, conversion specifiers, or both.

Below is list of some common conversion specifiers –

format string input type
%c character
%d digit (integer)
%f float
%lf double
%u unsigned
%s string

The scanf() function

he scanf() function is used for reading formatted input from the “stdin” data stream.It reads the string as per the format specified.

Syntax:

Example: