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.
scanfis the function name. It reads formatted input from the keyboard."%d"is the input format. It says what to read:%dmeans a whole number (int).&board_idis 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.
Prompt, read, echo
This is the basic pattern of every input program:
- Prompt:
printftells the user what to type. No\n, so the cursor waits on the same line. - Read:
scanfstops the program, waits for the user to type and press Enter, converts the input and stores it. - Echo:
printfprints 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: 417In 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.
| Step | Console | board_id |
|---|---|---|
int board_id; | (empty) | ? |
prompt: printf | Enter board ID: | ? |
| read: the user types 417 | Enter board ID: 417 | 417 |
echo: printf | You entered: 417 | 417 |
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 failedThe 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_WARNINGSOr 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 VThe user can separate the values with a space or with Enter (417, Enter, 4.98). The result is the same.
Read a double with %lf
voltage is a double, so scanf reads it with %lf, but printf prints it with %f:
| Code | Why | |
|---|---|---|
read a double | scanf("%lf", &voltage); | scanf writes into the variable, so it must know its exact type. %f is for float, %lf for double. |
print a double | printf("%.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 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: BThe \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:
| ID | Voltage | Channel | The ticket shows | What it checks |
|---|---|---|---|---|
| 417 | 4.98 | B | Voltage: 4.98 V | a typical board |
| 0 | 0 | a | Voltage: 0.00 V | zero values |
| 9001 | 12.345 | Z | Voltage: 12.35 V | rounding 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
| English | Hebrew | Meaning |
|---|---|---|
| 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.