Read user input into variables with scanf. Learn why & matters, the %lf gotcha, and the typical bugs.
scanf("%d", &x); reads into a variable& before the variable%lf (not %f!)fgets (safer)printf "sends text to the screen", scanf "reads input from the keyboard". It's the mirror image.printf("%d\n", a); // print variable a to screen
scanf("%d", &a); // read from keyboard into variable a
int a; printf("Enter a: "); // prompt scanf("%d", &a); // read input printf("a = %d\n", a);
& (ampersand) is required& before every variable. Forgetting it typically crashes the program.&int a; scanf("%d", a); // β forgot &
& really is: the variable's "address"a holds a value. &a is "the memory address where a lives".&a).
&; never prefix printf's. (printf only reads values; it doesn't need an address.) The detailed mechanism is covered in Pointer Basics.char name[50]; scanf("%s", name); // β no & for array name
%lf. Different from printf, and a classic source of confusion.| Type | scanf specifier | printf specifier |
|---|---|---|
int | %d | %d |
float | %f | %f |
double | %lf β οΈ | %f (%lf also OK) |
char | %c | %c |
| string | %s | %s |
%f for a doubledouble b; scanf("%f", &b); // β double needs %lf
b ends up with a completely wrong value (often 0.0 or huge). It's undefined behaviour. Compile with -Wall to get warnings.
%lf (the l is for "long"). Only scanf is picky here.&scanf("%d", &a);& usually crashes%f for doublescanf("%lf", &b);scanf("%d\n", &a); β no \nscanf("Enter %d", &a); β no prose%c with other specifiers.int a; double b; printf("Enter int: "); scanf("%d", &a); printf("Enter double: "); scanf("%lf", &b); // lf! printf("a=%d, b=%f\n", a, b);
int a; if (scanf("%d", &a) != 1) { printf("Please enter an integer\n"); return 1; }
& to see the crash (educational)%f and watch the value corruptscanf("%d %d", &a, &b); to read two ints separated by spacechar with %cchar s[50] with %s (stops at space)