UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

8.3.3.  The scanf function

The scanf function can be used to read various types of input data, such as integers, floats or strings.

#include <stdio.h>
int scanf(const char *format,...);

Here various format specifiers can be included inside the format string referenced by the char pointer variable format, as with printf. If the scanf function concludes successfully, it returns the number of data items read from stdin. If an error occurs, the scanf function returns EOF.

Using the string format specifier %s tells the scanf function to continue reading characters until a space, a newline, a tab, a vertical tab, or a form feed is encountered. Characters read are stored into an array that should be big enough to store the input characters. A null character is automatically appended to the array after the string is read.

Note

As with gets, it is very dangerous to use scanf to read strings entered by the user, because scanf does not pay attention to the length of the typed strings, and it will admit a string longer than the size defined for the array into which that string is going to be saved. As a result, scanf will write the remained characters in other memory slots which may have data being used by the program. This will eventually produce anomalous behaviours, memory leaks, etc. Later on we will see how to read user input in a secure way.

With scanf, unlike printf, you must pass pointers to your arguments so that the scanf function can modify their values.

The following program shows how to use scanf with various format specifiers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#define MAX_LENGTH 80

int main(void)
{
  char string[MAX_LENGTH];
  int integer1, integer2;
  float float_number;

  printf("Enter two integers separated by a space: \n");
  scanf("%d %d", &integer1, &integer2);
  printf("Enter a floating-point number:\n");
  scanf("%f", &float_number);
  printf("Enter a string:\n");
  scanf("%s",string);
  printf("This is what you have entered:\n");
  printf("%d %d %f %s\n",integer1,integer2,float_numer,string);
  return 0;
}

Notice that line 15 uses the scanf function to read a series of characters, and then saves these characters (plus a null character as the terminator) into the array pointed to by string. However, the address-of operator & is not used here, since the name of an array (string in this example) points (is equivalent) to the starting address of the array.