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. They're mirror images of each other.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);
printf β β‘ read with scanf β β’ use the value. This three-step pattern is the bread and butter of console I/O.& (ampersand) is requiredscanf: put & in front of every variable. Forgetting it usually crashes the program.&int a; scanf("%d", a); // β forgot &
& actually is: the variable's "address"a holds a value. &a is the memory address where a lives.scanf needs to know where to put the new value,&a).
&, and never prefix printf's. (printf just reads the value β it doesn't need an address.) The full mechanics are covered in Pointer Basics.char name[50]; scanf("%s", name); // β no & for array name
scanf, double uses %lf. That's different from printf, and it's 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 something huge). It's undefined behavior. Compile with -Wall to catch these.
%lf (the l stands for "long"). Only scanf is picky about this.scanf would store it.&scanf("%d", &a);& will usually crash the program%f for doublescanf("%lf", &b);scanf, double needs %lfscanf("%d\n", &a); β don't add \nscanf("Enter %d", &a); β don't embed 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);
scanf returns the number of items it successfully read, which is handy for catching bad input.int a; if (scanf("%d", &a) != 1) { printf("Please enter an integer\n"); return 1; }
& on purpose to see the crash (it's a useful lesson)%f and watch the value get corruptedscanf("%d %d", &a, &b); to read two ints separated by a spacechar with %cchar s[50] with %s (it stops at whitespace)Check your understanding of this lesson!
int x;?scanf needs the address where it should write the value, so prefix the variable name with &.
& needed on scanf arguments?scanf updates the caller's variable, so it needs a pointer (an address) rather than the value itself.
char name[50];?Array names decay to the address of their first element, so & isn't needed. %s reads a single word up to whitespace.