The scanf function allows the C language to read formatted data from the standard input. The usage is as follows: define the variables that need to read the data. Specifies a format string containing appropriate format specifiers such as %d (integer), %f (floating point), %c (character), %s (string). Call the scanf function, passing the format string as the first argument and the variable address as subsequent arguments. The scanf function returns the number of input items read on success, otherwise it returns a negative number to indicate an error or abort.
Usage of scanf in C language
scanf is a format used in C language to read from standard input function to transform data. It allows programmers to read a variety of data types, including integers, floating point numbers, characters, and strings, in specified formats.
Usage
The basic syntax of the scanf function is as follows:
<code class="c">int scanf(const char *format, ...);</code>
Among them:
format
: A pointer to a formatted string, specifying the data type and format to be read. ...
: Optional variable parameter list, the pointer points to the data variable that needs to be read. Format specifiers
The format string contains format specifiers, each format specifier specifies the data type and format to be read. Common format specifiers include:
%d
: Signed decimal integer %u
: Unsigned decimal integer %f
: floating point number %c
: character %s
: string Reading data
To read data using scanf, follow these steps:
Example
The following example shows how to use scanf to read integers and floating point numbers from the user:
<code class="c">int main() { int age; float weight; printf("请输入您的年龄和体重:"); scanf("%d %f", &age, &weight); printf("您的年龄是:%d,体重是:%.2f\n", age, weight); return 0; }</code>
Return results
The scanf function returns the number of input items read. If all input items were read successfully, returns the number of items read. Otherwise, a negative number is returned, indicating an error or the read was aborted.
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!