90 min

scanf: reading input

Read values from the keyboard into variables: & and the address, the prompt-read-echo pattern, %lf for double, a space before %c after a number, the C4996 error in Visual Studio, and a complete intake ticket.

Input needs a place to land

In the printf lesson the program talked to the user. Now the user talks back: scanf reads what the user types and stores it in a variable.

A variable (משתנה) is named storage. Its type decides what it can hold: int holds a whole number.

int board_id;

After this line, board_id exists, but its value is unknown. We write it as ?. It is not 0: it is whatever was in that memory before. Only after scanf does it hold the number the user typed.

Anatomy of a scanf call

scanf("%d", &board_id);

Read it as a sentence: read an integer and store it at the address of board_id.

  • scanf is the function name. It reads formatted input from the keyboard.
  • "%d" is the input format. It says what to read: %d means a whole number (int).
  • &board_id is the destination address (כתובת): where to store the number.
  • The semicolon ; ends the statement.

scanf looks like printf, with one big difference: after the format string, printf gets values, and scanf gets addresses.

& gives scanf the address

Every variable lives at an address in memory, like a house number. The & operator means "the address of". &board_id is the address of board_id.

scanf needs the address because it writes into the variable. When the user types 417 and presses Enter, scanf turns the characters 4, 1, 7 into the number 417 and writes it at that address.

Step through it: the arrow is the address that &board_id gives scanf; then the user types 417 and the number travels into the variable at that address. The addresses 1000, 1004, 1008 are only for the picture; real ones are long hexadecimal numbers.Open full screen

Prompt, read, echo

This is the basic pattern of every input program:

  1. Prompt: printf tells the user what to type. No \n, so the cursor waits on the same line.
  2. Read: scanf stops the program, waits for the user to type and press Enter, converts the input and stores it.
  3. Echo: printf prints the stored value back, to show it arrived.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int board_id;
 
    printf("Enter board ID: ");
    scanf("%d", &board_id);
    printf("You entered: %d\n", board_id);
    return 0;
}
Enter board ID: 417
You entered: 417

In the console, 417 is what the user typed. The first line of the program is explained in the next section.

A trace table (טבלת מעקב) shows the same run step by step: what is on the console and what is in memory after each step.

StepConsoleboard_id
int board_id;(empty)?
prompt: printfEnter board ID: ?
read: the user types 417Enter board ID: 417417
echo: printfYou entered: 417417

Input changes memory. Output shows what is in memory.

Visual Studio and C4996

When you build a program with scanf in Visual Studio 2022, the build fails:

main.c(6,5): error C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
Build: 0 succeeded, 1 failed

The code is correct C. C4996 is really a warning: Visual Studio prefers its own function scanf_s, and its security checks (on by default in new projects) turn the warning into an error. We keep scanf, because the exam and the formula sheet use it, and scanf_s works only with Microsoft's compiler.

The fix: put this line at the very top of the file, before #include:

#define _CRT_SECURE_NO_WARNINGS

Or set it once for the whole project: Project, Properties, C/C++, Preprocessor, Preprocessor Definitions, add _CRT_SECURE_NO_WARNINGS.

One scanf, two values

One scanf can read several values: one conversion and one address for each, in order.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int board_id;
    double voltage;
 
    printf("Enter ID and voltage: ");
    scanf("%d %lf", &board_id, &voltage);
    printf("ID %d, voltage %.2f V\n", board_id, voltage);
    return 0;
}
Enter ID and voltage: 417 4.98
ID 417, voltage 4.98 V

The user can separate the values with a space or with Enter (417, Enter, 4.98). The result is the same.

Switch between the two ways of typing the input. Both fill board_id and voltage the same way.Open full screen

Read a double with %lf

voltage is a double, so scanf reads it with %lf, but printf prints it with %f:

CodeWhy
read a doublescanf("%lf", &voltage);scanf writes into the variable, so it must know its exact type. %f is for float, %lf for double.
print a doubleprintf("%.2f", voltage);printf only gets a copy of the value to display it. %f is enough.

With scanf("%f", &voltage); the program builds, but voltage gets a wrong value.

The Enter key is a character too

What the user types first goes into the input, character by character, including the Enter key. %d reads the digits and stops at the first character that is not part of a number. The Enter stays in the input.

That is a problem when the next scanf reads a char:

scanf("%d", &board_id);
scanf("%c", &channel);

The user types 417 and Enter. %d reads 417. Then %c reads exactly one character, whatever it is: the leftover Enter. channel gets '\n', and the program runs on without waiting for the letter.

The fix is one space before %c:

scanf("%d", &board_id);
scanf(" %c", &channel);

A space in a scanf format means "skip any whitespace (רווח לבן) here": spaces, tabs and Enters. So " %c" skips the leftover Enter, waits, and reads the real letter.

The input row shows the characters waiting to be read. Watch %d take 4, 1, 7 and leave the Enter behind, and %c take it.Open full screen

The intake ticket

The complete program reads three values with three prompt-read pairs, then prints a ticket:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int board_id;
    double voltage;
    char channel;
 
    printf("Enter board ID: ");
    scanf("%d", &board_id);
    printf("Enter voltage: ");
    scanf("%lf", &voltage);
    printf("Enter channel: ");
    scanf(" %c", &channel);
 
    printf("\n--- Intake Ticket ---\n");
    printf("Board: %d\n", board_id);
    printf("Voltage: %.2f V\n", voltage);
    printf("Channel: %c\n", channel);
    return 0;
}
Enter board ID: 417
Enter voltage: 4.98
Enter channel: B
 
--- Intake Ticket ---
Board: 417
Voltage: 4.98 V
Channel: B

The \n at the start of the ticket line leaves an empty line between the questions and the ticket.

Testing

A program is tested with more than one input:

IDVoltageChannelThe ticket showsWhat it checks
4174.98BVoltage: 4.98 Va typical board
00aVoltage: 0.00 Vzero values
900112.345ZVoltage: 12.35 Vrounding to two digits

In this unit we assume the user always types the right kind of value. Later, conditions will let the program catch wrong input.

Key words

EnglishHebrewMeaning
variableמשתנהnamed storage with a type
addressכתובתwhere a variable lives in memory
& (address of)אופרטור הכתובת&board_id is the address of board_id
promptהודעת בקשהa message that tells the user what to type
echoהדפסה חוזרתprinting the value back to show it arrived
whitespaceרווח לבןspace, tab and Enter
trace tableטבלת מעקבthe values after each step of a program
warningאזהרהa message from the compiler; C4996 is the scanf one

Practice

All answers, and more debugging questions, are on the practice page.