scanf() Read formatted data from stdin
scanf() Read formatted data from stdin
scanf() returns EOF if an input failure occurs before the first conversion (if any) has completed. Bound %s/scanset widths; leave destination room for \0.
| Category | stdio.h I/O |
|---|---|
| Kind | Library function |
| Header | <stdio.h> |
| C standard | C89 / C90 |
📝 Syntax
int scanf(const char *format, ...);
⚙️ Parameters
| format Required | A format string containing whitespace, ordinary characters, and conversion specifiers. |
|---|---|
| ... Optional | Variable pointer arguments for storage, matching the corresponding conversion specifiers. |
Returns: Returns the number of input items assigned successfully, or EOF if an input failure occurs before the first conversion (if any) has completed. A matching failure can produce 0.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
Sample session with input 20 1.75:
Enter age and height: Age: 20
Height: 1.75
⚠️ Warning Always check the return value and pass addresses for numeric objects. For %s, specify a maximum field width, such as %31s for char s[32], to prevent overflow.
💡 Tip The output illustrates one interactive session; actual input comes from the user. For reading an entire line, fgets() is often more convenient.
🏷️ Related stdio.h functions
📚 Related Tutorials
❓ FAQ
QWhy does scanf need an ampersand before a variable?
Ascanf modifies the caller's objects, so numeric variables require addresses, as in &age. An array passed for %s already decays to a pointer to its first element, so no & is added.
QWhy does scanf with %s stop at whitespace?
A%s reads a sequence of non-whitespace characters, so it stops at spaces and newlines. Read the whole line first when spaces must be preserved.
QWhat do scanf return values of 0 and EOF mean?
AA return value of 0 usually means matching failed before any assignment, such as when a letter is encountered while an integer is expected. EOF means an input failure occurred before the first conversion was completed, either end-of-file or a read error; use feof() and ferror() to distinguish them, and discard the remaining input that caused the mismatch.