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.

Categorystdio.h I/O
KindLibrary function
Header<stdio.h>
C standardC89 / C90

📝 Syntax

int scanf(const char *format, ...);

⚙️ Parameters

format RequiredA format string containing whitespace, ordinary characters, and conversion specifiers.
... OptionalVariable 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏