Formatted Input

This lesson explains how the format of data can be specified at the time of input.

What is formatted input? #

It is possible to specify the format of the data expected to be read as input using readf. It specifies both the data that should be read and the characters that should be ignored.

D’s input format specifiers are similar to the ones present in the C language. As previously used, the format specifier " %s" reads the data according to the type of the variable. For example, since the type of the variable used in readf is double, the characters read at the input would be treated as a floating point number:

double number;
readf(" %s", &number);

The format string can contain three types of information:

  • The space character: indicates zero or more whitespace characters at the input and specifies that all of those characters should be read and ignored.

  • Format specifier: similar to the output format specifiers, input format specifiers start with the % character and determine the format of the data that is to be read.

  • Any other character: the characters that are expected at the input as is; they should be read and ignored.

The format string makes it possible to select specific information from the input and ignore the rest.

Let’s look at an example that uses all of the three types of information in the format string. Let’s assume that the student number and the grade are expected to appear at the input in the following format:

number:123 grade:90

Let’s further assume that the tags number: and grade: must be ignored. The following format string would select the values of number and grade and would ignore the other characters:

int number;
int grade;
readf("number:%s grade:%s", &number, &grade);

The format characters "number:%s grade:%s" must appear at the input exactly as specified; readf() reads and ignores them.
The single space character that appears in the format string above would cause all of the whitespace characters that appear exactly at that position to be read and ignored.
As the % character has a special meaning in format strings, when that character itself needs to be read and ignored, it must be written twice in the format string as %%.

Reading a single line of data from the input has been recommended as strip(readln()) in the strings lesson. Instead of that method, a \n character at the end of the format string can achieve a similar goal:

Note: Provide all the inputs before running the code.

Get hands-on with 1200+ tech skills courses.