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)".
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
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:
#includeint 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
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##↙
means pressing the Enter key.
%dseparated 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.
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!