In this tutorial you will learn about the C Input & Output and its application with practical example.
Input & Output is the way general-purpose computers can communicate or interact with the outside world. In C Programming Language input & output is the way a program can read in or write out data streams. Streams can be used for both un-formatted and formatted input and output.
To perform standard input and output, we need to include the following preprocessor directive into our files.
1 |
#include<stdio.h> |
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 the file.
putchar() function is used to write a single character to the “stdout” data stream. It puts a single character at a time, we can loop it for writing multiple characters.
Example:
1 2 3 4 5 6 7 8 9 10 |
#include <stdio.h> int main( ) { int c; printf( "Enter a value :"); c = getchar( ); printf( "\nYou entered: "); putchar( c ); return 0; } |
Reading and writing string
The gets() function reads the input data stream until the EOF is determined, while the puts() function is used to write a string to the “stdout” stream until a newline character is detected.
Syntax:
1 2 3 4 5 |
//gets() char *gets(char *s) //puts() int puts(const char *s) |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <stdio.h> int main( ) { char str[50]; printf( "Enter the string:"); gets( str ); printf( "\nYou entered: "); puts( str ); return 0; } |
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:
1 |
int printf(const char *format, ...) |
Example:
1 2 |
int number = 6; printf("the number is %d\n\n",number); |
The above printf statement contains two sets of arguments: the control string enclosed in double-quotes, and identifiers to specify the value to be printed. The control string contains text, conversion specifiers, or both.
Below is the 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
The scanf() function is used for reading formatted input from the “stdin” data stream. It reads the string as per the format specified.
Syntax:
1 |
int scanf(const char *format, ...) |
Example:
1 |
cnt = scanf("%d",&x); |