C++ scanf Functions Guide
In C++, the scanf function is used to read data from standard input and store it in variables. It can perform the following functions:
- To read an integer: use the format specifier “%d” or “%i” to read an integer value and store it in an integer variable. For example:
int num;
scanf("%d", &num);
- Reading floating point numbers: Use the format specifier “%f” to read a floating point value and store it in a floating point variable. For example:
float num;
scanf("%f", &num);
- Reading characters: Use the format specifier “%c” to read a character and store it in a character variable. For example:
char ch;
scanf("%c", &ch);
- Reading a string: Use the format specifier “%s” to read a string and store it in a character array. For example:
char str[100];
scanf("%s", str);
- Reading multiple values: You can use multiple format specifiers to read multiple values and store them in corresponding variables. For example:
int num1, num2;
scanf("%d %d", &num1, &num2);
It is important to note that the scanf function has strict requirements for the input format, so data must be entered according to the specified format. Additionally, to avoid potential errors, it is recommended to add a space before the format specifier when reading characters or strings, in order to ignore leading whitespace. For example:
char ch;
scanf(" %c", &ch); // 注意空格的使用