How to Take Input from User in C: Simple Guide
In C, you take input from the user using the
scanf function, which reads formatted data from the keyboard. You provide a format specifier like %d for integers or %s for strings, and pass the address of the variable where the input will be stored.Syntax
The basic syntax to take input in C is:
scanf("%format_specifier", &variable);Here:
- %format_specifier tells
scanfwhat type of data to expect (e.g.,%dfor int,%ffor float,%cfor char,%sfor string). - &variable is the address of the variable where the input will be stored. The
&symbol means "address of".
c
scanf("%d", &number);Example
This example shows how to take an integer input from the user and print it back:
c
#include <stdio.h> int main() { int number; printf("Enter a number: "); scanf("%d", &number); printf("You entered: %d\n", number); return 0; }
Output
Enter a number: 42
You entered: 42
Common Pitfalls
- Forgetting the
&before the variable name causes errors becausescanfneeds the variable's address. - Using wrong format specifiers leads to incorrect input reading or program crashes.
- Reading strings with
%sstops at the first space, so it cannot read multi-word inputs. - Not checking the return value of
scanfcan hide input errors.
c
#include <stdio.h> int main() { int number; // Wrong: missing & // scanf("%d", number); // This will cause a compile error or crash // Correct: scanf("%d", &number); return 0; }
Quick Reference
| Format Specifier | Data Type | Description |
|---|---|---|
| %d | int | Reads an integer |
| %f | float | Reads a floating-point number |
| %lf | double | Reads a double precision float |
| %c | char | Reads a single character |
| %s | char array | Reads a string (no spaces) |
Key Takeaways
Use scanf with the correct format specifier and the address of the variable to read user input.
Always include the & operator before variables except for arrays when using scanf.
Check the format specifier matches the variable type to avoid errors.
Remember that %s reads only up to the first space; use other methods for full lines.
Common mistakes include missing & and wrong format specifiers.