C Input and Output - printf()/scanf(), and more.
C Input and Output - printf()/scanf(), and more.
- Input means to provide the program with some data to be used in it.
- Output means to display data on the screen or write the data to a printer or a file.
- The C programming provides standard library functions to read any given input and display output on the console.
While dealing with input-output operations in C, we use the following two streams:
- Standard Input (stdin)
- Standard Output (stdout)
- Standard input or stdin is used for taking input.
- Standard output or stdout is used for giving output.
- The functions used for standard input and output are present in the stdio.h header file.
- Hence, to use those functions, we need to include the stdio.h header file in our program, as shown below.
#include <stdio.h>Functions Used for Input and Output
C language offers us several built-in functions for performing input/output operations. The following are the functions used for standard input and output:
printf()function - Show Outputscanf()function - Take Inputgetchar()andputchar()functiongets()andputs()function
In C Language, output devices like computer monitors, printers, etc. are treated as files and the same process is followed to write output to these devices as would have been followed to write the output to a file.
1. The printf() function
- The
printf()function is the most used function in the C language. - This function is defined in the stdio.h header file and is used to show output on the console (standard output).
Following is how the printf() function is defined in the C stdio.h library.
int printf(const char *format, ...);- It writes the C string pointed by the format pointer to the standard output (stdout).
- On success, the total number of characters written is returned.
- This function is used to print a simple text sentence or value of any variable which can be of
int,char,float, or any other datatype.
printf() Code Examples
Let's start with a simple example.
1. Print a sentence
Let's print a simple sentence using the printf() function.
#include <stdio.h>
int main() {
// using printf()
printf("Welcome to HCL GUVI");
return 0;
}Welcome to HCL GUVI
This one is a very common code example.
2. Print an Integer value
We can use the printf() function to print an integer value coming from a variable using the %d format specifier.
For example,
#include <stdio.h>
int main() {
int x = 10;
// using printf()
printf("Value of x is: %d", x);
return 0;
}Value of x is: 10
- In the program, above we have used the
%dformat specifier, to specify the type of value that will be added there. - The format specifiers
%dand%iare used for integer values.
3. Print a Character value
The %c format specifier is used to print character variable values using the printf() function.
#include <stdio.h>
int main() {
// using printf()
char gender = 'M';
printf("John's Gender is: %c", gender);
return 0;
}John's Gender is: M
4. Print a Float and a Double value
In the code example below, we have used the printf() function to print values of a float and double type variable.
For float value we use the %f format specifier and for double value we use the %lf format specifier.
#include <stdio.h>
int main() {
// using printf()
float num1 = 15.50;
double num2 = 15556522.0978678;
printf("Value of num1 is: %f \n", num1);
printf("Value of num2 is: %lf", num2);
return 0;
}Value of num1 is: 15.500000 Value of num2 is: 15556522.097868
We have used the \n Escape sequence which is used for a newline at the end of the first printf() statement so that the next printf() statement output is shown in the next line.
5. Print multiple outputs
We can use a single printf() function to display values of multiple variables.
#include <stdio.h>
int main() {
// using printf() for multiple outputs
int day = 20;
int month = 11;
int year = 2021;
printf("The date is: %d-%d-%d", day, month, year);
return 0;
}The date is: 20-11-2021
As you can see in the code example above, we can do the formatting and print values of multiple variables using the printf() function.
We can also perform some simple calculations inside printf(). Here is a simple example of that,
#include <stdio.h>
int main()
{
int a = 5, b = 6;
printf("%d", a + b);
return 0;
}Output:
11
Format Specifiers
- To print values of different data types using the
printf()statement and while taking input using thescanf()function, it is mandatory to use format specifiers. - It is a way to tell the compiler what type of data is in a variable.
- Some examples are
%c,%d,%f, etc.
Here is a list of all the format specifiers.
| Datatype | Format Specifier |
|---|---|
int |
%d, %i |
char |
%c |
float |
%f |
double |
%lf |
short int |
%hd |
unsigned int |
%u |
long int |
%li |
long long int |
%lli |
unsigned long int |
%lu |
unsigned long long int |
%llu |
signed char |
%c |
unsigned char |
%c |
long double |
%Lf |
2. The scanf() function
When we want to take input from the user, we use the scanf() function and store the input value into a variable.
Following is how the scanf() function is defined in the C stdio.h library.
int scanf(const char *format, ...);- It reads data from stdin and stores it according to the parameter format into the locations pointed by the additional arguments.
- On success, the function returns the number of items of the argument list successfully filled.
- The
scanf()function can be used to take input of any type from the user. - All you have to take care of is that the variable in which you store the value should have the same data type.
Here is the syntax for scanf():
scanf("%x", &variable);where, %x is the format specifier.
- Using the format specifier, we tell the compiler what type of data to expect from the user.
- The
&is the address operator which tells the compiler the address of the variable so that the compiler can store the user input value at that address.
scanf() Code Examples
Let's start with a simple example.
1. Input Integer value
If we have to take an integer value input from the user, we have to define an integer variable and then use the scanf() function.
#include <stdio.h>
int main() {
// using scanf()
int user_input;
printf("Please enter a number: ");
scanf("%d", &user_input);
printf("You entered: %d", user_input);
return 0;
}Please enter a number: 7 You entered: 7
NOTE: If you use our compiler, then while running the code example above, there is a button for Input at the top-right corner of the editor, you can click on it and provide custom value for input.
- In the above code example, we have used
%dformat specifier to inform thescanf()function that user input will be of type int. - And we have also used
&symbol before the name of the variable, because&user_inputrefers to the address of theuser_inputvariable where the input value will be stored.
2. Input Float value
Just like integer value, we can take input for any different datatype. Let's see an example of float type value.
#include <stdio.h>
int main() {
// using scanf()
float user_input;
printf("Please enter a decimal number: ");
scanf("%f", &user_input);
printf("You entered: %f", user_input);
return 0;
}Please enter a decimal number: 7.007 You entered: 7.007
- We have used the
%fformat specifier and defined afloattype variable. - Try doing the same for taking a
doubletype value as user input. - The format specifier for
doubleis%lf.
3. Input Character value
Let's see how we can take a simple character input from the user.
#include <stdio.h>
int main() {
// using scanf()
char gender;
printf("Please enter your gender (M, F or O): ");
scanf("%c", &gender);
printf("Your gender: %c", gender);
return 0;
}Please enter your gender (M, F or O): M Your gender: M
4. Take Multiple Inputs from the User
In the below code example, we are taking multiple inputs from the user and saving them into different variables.
#include <stdio.h>
int main() {
// using scanf() for multiple inputs
char gender;
int age;
printf("Enter your age and then gender(M, F or O): ");
scanf("%d %c", &age, &gender);
printf("You entered: %d and %c", age, gender);
return 0;
}Enter your age and then gender(M, F or O): 32 M You entered: 32 and M
Return Value of printf() & scanf()
- The
printf()function returns the number of characters printed by it, - and
scanf()function returns the number of characters read by it.
int i = printf("HCLGUVI");
printf("Value of i is: %d", i);HCLGUVIValue of i is: 12
- In this program
printf("HCLGUVI");will return7as a result, which will be stored in the variablei, because the word HCLGUVI has 7 characters. - The first
printf()statement will print the statement HCLGUVI on the output too.
3. getchar() & putchar() functions
The getchar and putchar functions are used for taking character input from the user and printing the character as output.
The getchar() function
- The
getchar()function reads a character from the terminal and returns it as an integer. - This function reads only a single character at a time.
Here is the syntax for the getchar() function:
int getchar(void);You can use this method in a loop if you want to read more than one character.
The putchar() function
- The
putchar()function displays the character passed to it on the screen and returns the same character. - This function too displays only a single character at a time.
Here is the syntax for the putchar() function:
int putchar(int character);In case you want to display more than one character, use putchar() method in a loop.
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
/*
Take a character as input and
store it in variable c
*/
c = getchar();
/*
display the character stored
in variable c
*/
putchar(c);
}Enter a character: HCLGUVI
When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will display the value you have entered.
4. gets() & puts() functions
The gets and puts functions are used for taking string input and giving string output.
The gets() function
The gets() function reads a line of text from stdin(standard input) into the buffer pointed to by str pointer, until either a terminating newline or EOF (end of file) occurs.
Here is the syntax for the gets() function:
char* gets(char* str);The puts() function
The puts() function writes the string str with a newline character ('\n') at the end to stdout. On success, a non-negative value is returned.
Here is the syntax for the gets() function:
int puts(const char* str);str is the pointer to an array of chars where the C string is stored (Don't worry if you are not able to understand this now.)
#include <stdio.h>
void main()
{
/* character array of length 100 */
char str[100];
printf("Enter a string: ");
gets(str);
puts(str);
getch();
return 0;
}Enter a string: HCLGUVI HCLGUVI
- When you will compile the above code, it will ask you to enter a string.
- When you will enter the string, it will display the value you have entered.
The gets() function is considered dangerous to use and should be avoided. We get a warning when we compile any code in which we have used gets() function. This is because the function doesn't know how big the buffer is, so it continues reading until it finds a newline or encounters EOF, and may overflow the bounds of the buffer it was given. We can use alternatives to gets() function, like the fgets() function.
The fgets() function
Here is the syntax for the fgets() function:
char* fgets(char* str, int num, FILE* stream);- It reads characters and stores them as a C string into
struntil (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first. - A newline character makes
fgetsstop reading, but it is considered a valid character by the function and included in the string copied tostr. - On success, the function returns the
str.
For example,
#include <stdio.h>
#define MAX 10
int main()
{
char str[MAX];
fgets(str, MAX, stdin);
printf("The string is: %s", str);
return 0;
}abcdefghijkl The string is: abcdefghij
Difference between scanf() and gets()
The main difference between these two functions is that scanf() stops reading characters when it encounters a space, but gets() reads space as a character too.
Let's see the scanf() function in action:
#include <stdio.h>
int main() {
// using scanf()
char n1[50], n2[50];
printf("Please enter n1: ");
scanf("%s", n1);
printf("You entered: %s", n1);
return 0;
}Now let's see the gets() function in action:
#include <stdio.h>
int main() {
// using scanf()
char n1[50], n2[50];
printf("Please enter n1: ");
gets(n1);
printf("You entered: %s", n1);
return 0;
}









