C language is a widely used programming language, and input is a very important part of the programming process. In C language, the scanf function is a function used to receive data from an input stream. This article will introduce the input format of the scanf function in detail and further explain it through specific code examples.
When using the scanf function for input, we need to use different format control characters to specify the input data type. The following are some commonly used format control characters and their corresponding data types:
Next, we illustrate the use of the scanf function through several specific examples.
Example 1: Receive integer data
int main() {
int num; printf("请输入一个整数:"); scanf("%d", &num); printf("您输入的整数是:%d
", num);
return 0;
}
In the above example, we used the %d format control character to receive integer data entered by the user. In the parameters of the scanf function, the & symbol needs to be used to obtain the num variable address in order to store the entered value into the variable.
Example 2: Receive floating point data
int main( ) {
float num; printf("请输入一个浮点数:"); scanf("%f", &num); printf("您输入的浮点数是:%f
", num);
return 0;
}
In Example 2, we use the %f format control character to receive floating-point data entered by the user. You also need to use the & symbol to get the address of the num variable.
Example 3: Receive character data
int main() {
char ch; printf("请输入一个字符:"); scanf("%c", &ch); printf("您输入的字符是:%c
", ch);
return 0;
}
In Example 3, use the %c format control character to receive character data entered by the user. You also need to use the & symbol to obtain the address of the ch variable.
Example 4: Receive string data
int main() {
char str[100]; printf("请输入一个字符串:"); scanf("%s", str); printf("您输入的字符串是:%s
", str);
return 0;
}
In Example 4, we used the %s format control character to receive string data entered by the user. There is no need to use the & symbol, just pass the address of the string directly to the scanf function.
To sum up, this article introduces the input format of the scanf function in C language and related code examples. By learning and becoming familiar with different format control characters, we can more flexibly handle different types of data input by users. I hope this article will help you learn input operations in C language.
The above is the detailed content of In-depth understanding of the scanf input format in C language. For more information, please follow other related articles on the PHP Chinese website!