Lesson 5 · 5 of 20
Reading input with scanf · C
Ask the user for data in C with scanf: words with %s, whole numbers with %d and decimals with %lf, and check how many values were read.

`scanf` is the opposite of printf: it reads from the keyboard following a format and stores what it reads in variables. Since it needs to know where to store it, numbers get an & in front: scanf("%d", &age). What that & means exactly comes in the lesson on pointers.
char name[30] makes room for some text (lesson 11 covers text in depth). %29s reads one word of up to 29 letters, leaving room for the end of the text; text does not take an &.
Watch out for double: in scanf it is read with `%lf`, even though printf writes it with %f. One format can read several values at once: "%d %d" reads two whole numbers from the same line, and scanf returns how many it managed to read, here 2. If someone typed a letter instead of a number it would return fewer, so you can check.
Here the answers come from the input.txt file, as if someone were typing them, so they do not appear in the output: you only see the questions and the program's replies. In the DMarlon Studio console, after pressing F9, you can type them yourself.
Code · main.c
#include <stdio.h>int main(void) { char name[30]; // room for a word of up to 29 letters int age; double price; int adults, children; // %s reads one word. Text needs no &. printf("What is your name? "); scanf("%29s", name); printf("Nice to meet you, %s!\n", name); // For numbers, &age tells scanf where to store the value. printf("How old are you? "); scanf("%d", &age); printf("In 10 years you will be %d.\n", age + 10); // %lf reads a double (printf writes it with just %f). printf("Price of a cinema ticket? "); scanf("%lf", &price); printf("One ticket: %.2f euros.\n", price); // Two numbers on one line; scanf returns how many it read. printf("Adult and child tickets? "); int read = scanf("%d %d", &adults, &children); printf("(scanf read %d numbers)\n", read); // Children pay half price. double total = price * adults + price / 2 * children; printf("%d tickets cost %.2f euros.\n", adults + children, total); return 0;}Input (what gets typed) · input.txt
Lucia 29 8.50 2 1
Output · cc main.c -o main && ./main
What is your name? Nice to meet you, Lucia! How old are you? In 10 years you will be 39. Price of a cinema ticket? One ticket: 8.50 euros. Adult and child tickets? (scanf read 2 numbers) 3 tickets cost 21.25 euros.
Key points
scanfreads with the same kind of formats asprintf.- Numbers take
&:scanf("%d", &n). - A
doubleis read with%lf. %29sreads a word without overflowing.scanfreturns how many values it read.
Exercise
Also ask for the screen number with %d and end with «Room 4: 3 tickets cost 21.25 euros.». Add the answer to input.txt.