To create programs that truly provide value, we need to allow users to interact with them. In C, the most common way to get user input is by using the scanf() function. However, depending on whether you are reading numbers, single characters, or full sentences, there are different methods you should use.
The scanf() function is used to take input from the standard input (usually the keyboard). It requires two things: a **format specifier** (to know what type of data to expect) and an **address operator** (&) to tell C where to store that data in memory.
The scanf() function allows you to accept multiple inputs in a single line. You simply list the format specifiers and provide the corresponding variable addresses.
When taking a string as input, you use the %s format specifier. **Crucially**, you do not need the & operator for strings because a string's name already represents its memory address.
scanf() function stops reading as soon as it encounters a whitespace (space, tab, or newline). If you type "John Doe", scanf() will only store "John".
To read a string that contains spaces (like a full name or a sentence), the fgets() function is the preferred choice. It is safer than scanf() because it prevents "buffer overflow" by allowing you to specify the maximum number of characters to read.
Using the correct specifier is mandatory. If you use %d for a float, your program will produce incorrect results or crash.
| Data Type | Format Specifier |
|---|---|
| Integer | %d |
| Float (Decimal) | %f |
| Character | %c |
| String (Words) | %s |
&, scanf() doesn't know where the variable is located in memory.scanf() can cause a subsequent %c input to be skipped. Professional coders often use fflush(stdin) or a space before the specifier (" %c") to fix this.