In C, reading data from the keyboard and storing variables is usually done through a standard input-output library (stdio.).h), the most commonly used function is:scanf
。This function can read different types of input data and store it in one or more variables according to the specified format.
scanf
The prototype of the function is as follows:
int scanf(const char *format, .
format
is a format string that specifies the type of data you want to read from user input.
Indicates that a function can accept multiple parameters, which are the addresses of variables
scanf
The data entered by the user is stored in the variables that these addresses point to.
Let's say you want to read an integer and a float from the keyboard and store them separately as variablesa
withb
, you can write **:
#include int main()In this example:
%d
is a format specifier that is used to read integers.
%f
is another format specifier that reads floating-point numbers.
&a
with&b
is a variablea
withb
address. In C, you need to provide the address of the variable in order to:scanf
Ability to store data into these variables.
usescanf
, you need to make sure that the variable type you provide matches the format specifier, otherwise you may end up with undefined behavior.
For reading strings, you can use it%s
format specifier, but be careful to prevent the risk of buffer overflow.
scanf
When the function is successfully read, it returns the number of items that were successfully read, and you can check whether the input is successful by this return value.
User input needs to be followedscanf
, otherwise it may cause the read to fail or the program behaves unexpectedly.
scanf
is a powerful but cautionary function, and using it correctly requires some knowledge of data types and memory management in C.