scanf in C++: Usage Guide
In C++, the scanf function is used to read formatted input from standard input. Its basic syntax is as follows:
#include <cstdio>
scanf(format, &variable1, &variable2, ...);
The format is a string used to specify the reading format of variables, where &variable1, &variable2, … are the addresses of the variables to be read.
For example, if you want to read an integer, you can use %d as the formatting string and provide the address of an integer variable to receive the input value:
#include <cstdio>
int main() {
int num;
scanf("%d", &num);
printf("输入的整数是:%d\n", num);
return 0;
}
The scanf function can accept multiple parameters to read the values of multiple variables. The format specifiers in the format string should match the types of variables. For example, to read two integers, you can use %d twice:
#include <cstdio>
int main() {
int num1, num2;
scanf("%d %d", &num1, &num2);
printf("输入的两个整数是:%d 和 %d\n", num1, num2);
return 0;
}
Please note that the scanf function returns the number of successfully read parameters. If the reading fails, the return value will be EOF (-1).
Additionally, when using the scanf function, be cautious about handling input buffer issues. As scanf leaves a newline character when reading formatted input, it may impact subsequent input. One option is to use the getchar function to clear the input buffer, or use cin.ignore (if using the C++ standard library for input and output) to ignore the newline character.