Home >Backend Development >C++ >How to use scanf in c language
The scanf function is used to read data from standard input. The specific steps are as follows: specify the format string and define the format of the data to be read. Put the variable into the variable parameter list and receive the read data. Check the return value to determine whether the data is read successfully or not.
How to use scanf to read input
scanf is used in C language to read data from standard input Library Functions.
Syntax:
<code class="c">int scanf(const char *format, ...);</code>
Among them:
: A string specifying the input format.
: Variable parameter list, specify the variable to read data from.
Usage steps:
Specify the format string : format string Specifies the format of the data to be read. For example:
: Read an integer
: Read a floating point number
: Read a string
#Put the variable into the variable parameter list : Use the variable to read the data as format The parameters after the string are passed to the
scanf function. For example:
<code class="c">int age; scanf("%d", &age); // 读取用户的年龄</code>
The function returns the number of successfully read items. If all specified items are read successfully, it returns a positive value equal to the number of conversion specifiers in the
format string. Otherwise, it returns a negative value (-1) or 0.
Example:
The following code example demonstrates how to use thescanf function to read the user's name and age:
<code class="c">#include <stdio.h> int main() { char name[50]; int age; printf("请输入您的姓名: "); scanf("%s", name); printf("请输入您的年龄: "); scanf("%d", &age); printf("您的姓名是 %s,年龄是 %d 岁。\n", name, age); return 0; }</code>
The above is the detailed content of How to use scanf in c language. For more information, please follow other related articles on the PHP Chinese website!