Input and Output in C
Last updated on September 24, 2020
As you already know, stdio.h
header file is required for input and output operations in C. In this chapter we will discuss two input functions: scanf()
and getchar()
and two output functions: printf()
and putchar()
. But first, we will study something called conversion specification because functions like scanf()
and printf()
use this facility.
Conversion Specification #
Conversion specifications are used to specify datatype. Each conversion specification begins with (%
) sign. Here are some common conversion specifications:
CONVERSION SPECIFICATION | DESCRIPTION |
---|---|
%c |
a single character |
%d |
an integer |
%f |
floating point number |
%x |
a hexadecimal integer |
%o |
an octal integer |
%i |
an integer, hexadecimal or octal |
%s |
a string |
%u |
an unsigned integer |
%h |
a short integer |
%lf |
a long range floating point number |
Outputting data #
The printf()
function is used to output data to the console. Syntax: printf("Control string", variable1, variable2 , ...);
Control string: It contains conversion specification and text enclosed in double quotes. This argument controls how the output will appear on the screen. Variables: variables whose data we want to print in the console. Instead of passing variables, we can also pass constants and expressions too. This parameter is optional. If the control string does not contain any conversion specification, then variables are not specified. Example 1: Printing Strings The following program prints a string to the console using the printf()
statement.
1 2 3 4 5 6 7 8 9 | #include<stdio.h>
int main()
{
printf("Control string with no conversion specification");
// signal to operating system everything works fine
return 0;
}
|
Expected Output:
Control string with no conversion specification
Here control string contains only text no conversion specification. So there is no need to specify any variable or expression.
Example 2: Printing integers
1 2 3 4 5 6 7 8 9 10 11 | #include<stdio.h>
int main()
{
int ival = 100;
printf("%d", ival);
// signal to operating system everything works fine
return 0;
}
|
Expected Output:
100
Here control string contains a single %d
character which means that an integer value will be displayed. We can also use text inside the control string along with conversion specification.
Example 3: Printing integers with along with some text
1 2 3 4 5 6 7 8 9 | #include<stdio.h>
int main()
{
int sal = 200000;
printf("Basic salary: %d", sal);
return 0;
}
|
Expected Output:
Basic salary: 10000
Here control string contains the text "Basic salary: "
along with conversion specification %d
. The text will be displayed as it is, and %d
is replaced by the actual value of the variable sal
.
Example 4: Printing floating-point numbers
1 2 3 4 5 6 7 8 9 | #include<stdio.h>
int main()
{
float ival = 3.14551;
printf("%f", ival);
// signal to operating system everything works fine
return 0;
}
|
Expected Output:
3.145510
Here control string contains a single %f
conversion specification character which means a floating point value will be displayed.
Example 5: Printing characters
1 2 3 4 5 6 7 8 9 | #include<stdio.h>
int main()
{
char ival = 'z';
printf("%c", ival);
// signal to operating system everything works fine
return 0;
}
|
Expected Output:
z
Here control string contains a single %c
conversion specification which means a character will be displayed.
Example 6: Printing arrays
1 2 3 4 5 6 7 8 9 10 | #include<stdio.h>
int main()
{
char str[] = "Testing printf()";
printf("%s", str);
// signal to operating system everything works fine
return 0;
}
|
Expected Output:
Testing printf()
Here control string contains a single %s
conversion specification which means a string will be displayed.
Example: 7
1 2 3 4 5 6 7 8 9 10 11 | #include<stdio.h>
int main()
{
int salary = 20000;
int expenses = 15000;
int saving = 5000;
printf("Salary: %d , Expenses: %d, Saving: %d", salary, expenses, saving);
return 0;
}
|
Expected Output:
Salary: 20000 , Expenses: 15000, Saving: 5000
Here control string contains text along with three conversion specification. In the general number of conversion specification and variable are equal, this is true for both scanf()
as well as printf()
function.
Example: 8
We already know that just like %d
is used to denote a decimal number. Similarly %o
and %x
is used to denote octal and hexadecimal numbers respectively.
1 2 3 4 5 6 7 8 9 | #include<stdio.h>
int main()
{
int num=100;
printf("Octal equivalent of %d = %o\n", num, num);
printf("Hexadecimal equivalent of %d = %x", num, num);
return 0;
}
|
Expected Output:
1 2 | Octal equivalent of 100 = 144
Hexadecimal equivalent of 100 = 64
|
Example 9: Printing newline
We have learned about escape sequences in earlier chapters. Let's see how we can use them to properly format our output. The following program demonstrates how we can properly format our data using escape sequences.
1 2 3 4 5 6 7 8 9 10 11 | #include<stdio.h>
int main()
{
int salary = 20000;
int expenses = 15000;
int saving = 5000;
printf("Salary: %d \nExpenses: %d \nSaving: %d\n", salary, expenses, saving);
return 0;
}
|
Expected Output:
1 2 3 | Salary: 20000
Expenses: 15000
Saving: 5000
|
When \n
newline character is encountered it moves the cursor to the beginning of next line and printing starts from there.
Example 10: Printing tabs
1 2 3 4 5 6 7 8 9 10 | #include<stdio.h>
int main()
{
int salary = 20000;
int expenses = 15000;
int saving = 5000;
printf("Salary: %d \tExpenses: %d \tSaving: %d", salary, expenses, saving);
return 0;
}
|
Expected Output:
Salary: 20000 Expenses: 15000 Saving: 5000
\t
is known as a tab character. When \t
is encountered it moves the cursor to the next tab stop. \t
is commonly used to display data in tabular form.
Example 11:
Another commonly used escape sequence is \"
, which represent "
character. Since "
character marks the beginning and end of a string, we can't use it directly inside a string.
1 2 3 4 5 6 7 | #include<stdio.h>
int main()
{
printf("Enough \"Hello World\" programs");
return 0;
}
|
Expected Output:
Enough "Hello World" programs
Example 12:
We know that \
marks the beginning of the escape sequence that's why we can't use it directly inside a string because the compiler will assume that it's is the beginning of the escape sequence. To print a single \
we have to use two \
characters inside a string.
1 2 3 4 5 6 7 | #include<stdio.h>
int main()
{
printf("Path : C:\\Users\\X");
return 0;
}
|
Expected Output:
Path : C:\\Users\\X
The \
escape sequence is commonly used to display Windows pathname.
Reading input from the keyboard #
The scanf()
function is used to read input from the keyboard.
Syntax: scanf("Control string", address1, address2 , ...);
You must pass at least two arguments to this function.
Control string: A string which contains one or more conversion specification enclosed in double-quotes. The number of conversion specifications depends on the number of variables we want to input.
The next parameter, address1
is the address of the variable, scanf()
function expects at least one address. The address of the variable can be found by preceding a variable name with (&
) sign.
In scanf()
function syntax ...
(known as ellipsis) indicates that scanf()
can accept variable number of arguments.
The following program demonstrates how to receive input from the keyboard using scanf()
function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include<stdio.h>
int main()
{
// declare variable i
int i;
// Ask user to enter a number
printf("Enter a number: ");
// accept input from keyboard
scanf("%d", &i);
// print the entered number
printf("You entered %d", i);
// signal to operating system everything works fine
return 0;
}
|
Expected Output:
1 2 | Enter a number: 99
You entered 99
|
In the above program, we want the user to enter a number that's why a single %d
conversion specification is used in scanf()
. If we want the user to enter a string we should use %s
. Similarly, use %c
for a single character and %f
for float
.
Reading a character #
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include<stdio.h>
int main()
{
// declare variable i
char ch;
// Ask user to enter a character
printf("Enter a character: ");
// accept input from keyboard
scanf("%c", &ch);
// print the entered character
printf("You entered %c", ch);
// signal to operating system everything works fine
return 0;
}
|
Expected Output:
1 2 | Enter a character: q
You entered q
|
Here control string contains a single %c
conversion specification, which means that a single character should be entered. Similarly, you can ask the user to enter a floating point number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include<stdio.h>
int main()
{
// declare variable i
float fp;
// Ask user to enter a floating point number
printf("Enter a floating point number: ");
// accept input from keyboard
scanf("%f", &fp);
// print the entered float point number
printf("You entered %f", fp);
// signal to operating system everything works fine
return 0;
}
|
Expected Output:
1 2 | Enter a floating point number: 212.3441
You entered 212.344101
|
Accepting more than one values #
A single scanf()
function can also be used to input more than one values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include<stdio.h>
int main()
{
// declare variable x and y
int x, y;
// Ask user to enter 2 number
printf("Enter two numbers: ");
// accept input from keyboard
scanf("%d%d", &x, &y);
// print the entered numbers
printf("Value of x = %d and y = %d", x, y);
// signal to operating system everything works fine
return 0;
}
|
Expected Output:
1 2 | Enter two numbers: 1100 3341
Value of x = 1100 and y = 3341
|
Here two %d
conversion specification characters are used which means two integer values should be entered. To enter two numbers simultaneously, you need to enter the first number press space then enter the second number.
1100 3341
When more than one value are input by scanf()
, these values can be separated by whitespace characters like space, tab or newline(default), but you can change this behavior by placing a specific character between conversion specification. Let’s take an example to illustrate this point.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include<stdio.h>
int main()
{
// declare variable x and y
int x, y;
// Ask user to enter 2 number
printf("Enter two numbers: ");
// accept input from keyboard
scanf("%d:%d", &x, &y);
// print the entered numbers
printf("Value of x = %d and y = %d", x, y);
// signal to operating system everything works fine
return 0;
}
|
Expected Output:
1 2 | Enter two numbers: 145:631
Value of x = 145 and y = 631
|
Here colon(:
) character is used between two %d
's. It means now you have to enter the first number then a colon(:
), followed by the second number.
The following program asks the user to enter three integers separated by a comma (,
).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include<stdio.h>
int main()
{
// declare variable x, y and z
int x, y, z;
// Ask user to enter 3 number
printf("Enter three numbers: ");
// accept input from keyboard
scanf("%d,%d,%d", &x, &y, &z);
// print the entered numbers
printf("Value of x = %d , y = %d, z = %d", x, y, z);
// signal to operating system everything works fine
return 0;
}
|
Expected Output:
1 2 | Enter three numbers: 341,881,4124
Value of x = 341 , y = 881, z = 4124
|
For better readability, we can include some spaces between conversion specification. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include<stdio.h>
int main()
{
// declare variable x, y and z
int x, y, z;
...
// accept input from keyboard
scanf("%d %d %d", &x, &y, &z);
...
}
|
Other than better readability they don't have any significance. So the above code is essentially the same as:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include<stdio.h>
int main()
{
// declare variable x, y and z
int x, y, z;
...
// accept input from keyboard
scanf("%d%d%d", &x, &y, &z);
...
}
|
Character I/O #
The getchar()
and putchar()
macros are used for character i/o in C, we will discuss what macros are in later chapters, but for now treat them as functions. The getchar()
reads a single character from the standard input i.e keyboard and putchar()
outputs one character to standard outputs i.e console.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // Program to input a character then print it
#include<stdio.h>
int main()
{
char ch;
printf("Enter a character: ");
ch = getchar();
printf("The entered character is: ");
putchar(ch);
// signal to operating system everything works fine
return 0;
}
|
Expected Output:
1 2 | Enter a character: a
The entered character is: a
|
In the next chapter, we will learn about Formatted Input and Output in C.
Deadly scanf() #
The scanf()
function contains several traps which we haven't discussed. Consider the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <stdio.h>
int main()
{
int n;
char ch;
printf("Enter a number: ");
scanf("%d", &n);
printf("Enter a character: ");
scanf("%c", &ch);
printf("\n\n");
printf("n = %d\n", n);
printf("c = %c\n", ch);
return 0;
}
|
Nothing extraordinary is going on here just a simple program asking the user to enter a number and a character, but that's a deception, run the program and see it yourself.
Expected Output:
1 2 3 4 5 | Enter a number: 100
Enter a character:
n = 100
c =
|
As soon as you enter a number program displays it without waiting for you to enter a character, why it is so ?
Let's discuss the scanf()
function in little more detail.
When the input is entered it is stored in a temporary memory called input buffer. Consider the following scanf()
call:
scanf("%d", %a);
Let's say user entered 445\n
. So now contents in the input buffer is:
445\n
Here we have provided %d
conversion specification which means we want to scanf()
to read a number. But since scanf()
doesn't know how long your number will be, so it keeps reading digits until it encounters a non-digit character ( in this case \n
). The scanf()
reads the \n
character since it's not a number, it pushes \n back the to input buffer.
At this point contents of the input buffer is:
\n
Here is the rule 1: The character that is pushed back to the input buffer will be read first by the subsequent calls of scanf()
.
So now we can explain what's going on in our program.
Let's say the user entered 100. So now contents of the input buffer are:
100\n
First, the scanf()
call in line 9 reads 100 and pushes \n
character back to the input buffer. Now the contents of the buffer are:
\n
The second scanf()
statement in line 12 reads the \n
character. So now variable ch
contains a newline character. We can verify this fact by printing the ASCII value of newline \n
character which is 10. Add the following print()
statement after the printf()
statement in line 17.
printf("ASCII value of c = %d\n", ch);
Run the program and enter the input as follows:
100\n
Expected Output:
1 2 3 4 5 6 | Enter a number: 100
Enter a character:
n = 100
c =
ASCII value of c = 10
|
This verifies the fact that ch contains a newline(\n
) character. Obviously, the question arises how to solve this problem?
It turns out that if there are one or more white-space characters in the control string, scanf()
repeatedly reads white-space characters from input buffer until a non-space character is encountered. A white-space character in a format string matches any number of white-space character in the input including none.
So if we add one or more white-space character just before %c
, this causes scanf()
to read all the white-space character before reading a character.
scanf(" %c", &ch); // notice the white-space preceding %c
Another solution is that just before reading the character flush the buffer using the following function.
fflush(stdin);
Calling this function removes all the data from the input buffer. Here is our modified program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <stdio.h>
int main()
{
int n;
char ch;
printf("Enter a number: ");
scanf("%d", &n);
printf("Enter a character: ");
scanf(" %c", &ch); // notice the space preceding %c
printf("\n\n");
printf("n = %d\n", n);
printf("c = %c\n", ch);
return 0;
}
|
Expected Output:
1 2 3 4 | Enter a number: 100
Enter a character: a
n = 100
c = a
|
Load Comments