Home  >  Article  >  Backend Development  >  What is the role of scanf in c language?

What is the role of scanf in c language?

青灯夜游
青灯夜游Original
2020-11-17 10:04:32197961browse

scanf() is an input function in C language. Its function is to obtain user input from the keyboard and input data from the keyboard into the specified variable in the format specified by the user; the basic syntax format is "scanf("format character", input parameters)".

What is the role of scanf in c language?

Related recommendations: C language video tutorial

scanf() function

scanf() is an input function in C language. Like the printf function, it is declared in the header file stdio.h, so #include ade979de5fc0e1ca0540f360a64c230b must be added when using the scanf function. (In some implementations, the printf function and scanf function can be used without using the precompiled command #include ade979de5fc0e1ca0540f360a64c230b.) It is a format input function, that is, inputting data from the keyboard into the among the specified variables.

scanf is the abbreviation of scan format, which means formatted scanning, that is, obtaining user input from the keyboard, which is exactly the opposite function of printf.

Let’s look at an example first:

#include <stdio.h>
int main()
{
    int a = 0, b = 0, c = 0, d = 0;
    scanf("%d", &a);  //输入整数并赋值给变量a
    scanf("%d", &b);  //输入整数并赋值给变量b
    printf("a+b=%d\n", a+b);  //计算a+b的值并输出
    scanf("%d %d", &c, &d);  //输入两个整数并分别赋值给c、d
    printf("c*d=%d\n", c*d);  //计算c*d的值并输出

    return 0;
}

Running result:

12↙
60↙
a+b=72
10 23↙
c*d=230

##↙ means pressing the Enter key.

Enter 12 from the keyboard, press the Enter key, scanf() will read the input data and assign it to variable a; after this input is completed, the next scanf() function will be executed, and then Enter 60 from the keyboard and press the Enter key, and 60 will be assigned to variable b, which is the same reason.

In the 8th line of code, scanf() has two

%d separated by spaces, followed by two variables. This requires us to enter two integers at once and assign them separately. Give c and d. Note that there are spaces between "%d %d", so there must be spaces when entering data. For scanf(), the format of the input data must be consistent with the format of the control string.

For more programming-related knowledge, please visit:

Programming Learning Course! !

The above is the detailed content of What is the role of scanf in c language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn