Basic usage and examples of scanf function in C language
Introduction:
In C language, scanf function is a commonly used input function, used for Get data from the standard input device (usually the keyboard) and store the data in a variable. This article will introduce the basic usage of the scanf function in detail and provide some specific code examples to help readers better understand and use the scanf function.
Basic usage:
The basic usage of the scanf function is to use the format control string to specify the type and order of the data to be input. The format control string consists of conversion specifiers and ordinary characters and is used to specify the format of the input data. The function prototype of the scanf function is as follows:
int scanf(const char *format, ...);
Among them, format
is the format control string, and the following ellipsis indicates optional parameters, which are used to specify the variable to store the data.
Specific examples:
The following are several common usage examples:
Example 1: Enter an integer
#include <stdio.h> int main() { int num; printf("请输入一个整数:"); scanf("%d", &num); printf("您输入的整数是:%d ", num); return 0; }
In the above example, is used %d
is used as a conversion specifier, indicating that the input is a decimal integer. The &
symbol is used to get the address of the variable num
so that the input value is stored at that address.
Example 2: Input a floating point number
#include <stdio.h> int main() { float num; printf("请输入一个浮点数:"); scanf("%f", &num); printf("您输入的浮点数是:%f ", num); return 0; }
The above example uses %f
as the conversion specifier, indicating that the input is a floating point number. Likewise, use the &
notation to get the address of the variable num
to store the entered floating point number.
Example 3: Input string
#include <stdio.h> int main() { char name[20]; printf("请输入您的名字:"); scanf("%s", name); printf("您好,%s! ", name); return 0; }
In this example, %s
is used as the conversion specifier, indicating that the input is a string. Here, the array name
is actually a character array used to store the input string. Note that for %s
, there is no need to use the &
symbol because the array name itself is already the address.
Tips and Notes:
Conclusion:
This article introduces the basic usage of the scanf function in C language and provides some specific code examples. I hope that through the introduction of this article, readers can better understand and use the scanf function, thereby improving the efficiency and accuracy of C language programming.
The above is the detailed content of Basic usage and examples: scanf function in C language. For more information, please follow other related articles on the PHP Chinese website!