Reading from the console

Location
  1. Courses

    /

  2. Quick C course

    /

  3. Reading from the console

We read from the console similarly to how we write to it using the function 'printf', but by using the function 'scanf' and by giving it the addresses of the variables we want it to store the data read into.

When a call of the function 'scanf' is reached, the execution of the program stops until there is something to read from the console.

Reading an integer number

Let us define a variable:

int var;

We read a number, from the console, to it:

scanf("%d", &var);

Reading a floating-point number

We read a floating-point number from the console:

float var; scanf("%f", &var);

Here we read a floating-point number and then print it:

main.c

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h> int main() { printf("Enter a number: "); float num; scanf("%f", &num); printf("You entered the number %f.\n", num); return 0; }

Reading a string

To read a string, we must give an array of char to the function 'scanf'. Note that if the array is not big enough to hold the text read (The null character at the end included), the program will crash.

We define an array of 50 characters:

char str[50];

We read a string, from the console, to it:

scanf("%s", str);

The types must match

Unlike 'printf', 'scanf' must receive pointers to variables that match exactly the types it expects.

The following would not work:

short int var; scanf("%d", &var);

Here is a table with some identifiers (Usable with both 'printf' and 'scanf'):

IdentifierType
%hdshort
%dint
%ldlong
%huunsigned short
%uunsigned
%ulunsigned long
%ffloat
%lfdouble

Note that, with 'printf', '%f' represents the type 'double'.

More information

The functions 'printf' and 'scanf' are quite complex. They can be configured in many ways.

If you wish, you will find a complete presentation of 'printf', here, and of 'scanf', here.