Reading Input from the Terminal
Reading input from the terminal allows your C programs to interact with users and receive data during runtime. In this section, we'll explore the standard input functions, particularly scanf()
, which is commonly used for reading input in C.
The scanf() Function
The scanf()
function is part of the standard input/output library in C and is used for reading formatted input. It allows you to receive user input and store it in variables. Here's a basic example:
In this example, %d
is the format specifier for an integer, and &age
represents the memory address of the age
variable.
Format Specifiers for scanf()
scanf()
supports various format specifiers for different types of input:
%d
: Integer%f
: Float%lf
: Double%c
: Character%s
: String
Reading Strings with Spaces
Reading strings with spaces using scanf()
requires a different approach. The %s
specifier stops reading at the first whitespace. Instead, you can use the %[^\n]
specifier to read a whole line:
Handling Multiple Inputs
To read multiple inputs in a single scanf()
call, you can use multiple format specifiers separated by spaces:
Conclusion
Reading input from the terminal is a crucial aspect of interactive C programming. The scanf()
function provides a flexible way to receive user input in various formats. Understanding the appropriate format specifiers and handling input effectively enhances the usability of your C programs.
In the upcoming sections, we'll explore more advanced concepts in C programming. If you have specific questions or areas you'd like to delve into further, feel free to ask. Happy coding!