scanf_s输入单个字符
To understand the functionally of scanf() while reading characters, we need to understand its flow, Consider the following statement:
要了解在读取字符时scanf()的功能,我们需要了解其流程,请考虑以下语句:
scanf ("%c%c%c", &x, &y, &z);
Now, if the input is "a b c", then 'a' will be assigned to variable x, SPACE will be assigned to variable y and 'b' will be assigned to variable z.
现在,如果输入为“ abc” ,则将'a'分配给变量x ,将SPACE分配给变量y ,将'b'分配给变量z 。
Thus, scanf() reads the characters as well as space, tab and new line character.
因此, scanf()读取字符以及空格 , 制表符和换行符 。
So to read character values after skipping spaces, tabs we need to skip any value between two character values and this is possible by using skip format specifier "%*c".
因此,要在跳过空格后读取字符值,制表符需要跳过两个字符值之间的任何值,这可以通过使用跳过格式说明符“%* c”来实现 。
Program 1: without skipping spaces between characters
程序1:不跳过字符之间的空格
#include <stdio.h>
int main(void)
{
char x;
char y;
char z;
//input
printf("Enter 3 character values: ");
scanf ("%c%c%c", &x, &y, &z);
//print
printf("x= \'%c\' \n", x);
printf("y= \'%c\' \n", y);
printf("z= \'%c\' \n", z);
return 0;
}
Output
输出量
Enter 3 character values: a b c
x= 'a'
y= ' '
z= 'b'
Here, x contains 'a', y contains ' ' (space) and z contains 'b'.
这里, x包含'a' , y包含'' (空格), z包含'b' 。
Program 2: By skipping spaces or any character between characters
程序2:通过跳过空格或字符之间的任何字符
#include <stdio.h>
int main(void)
{
char x;
char y;
char z;
//input
printf("Enter 3 character values: ");
scanf ("%c%*c%c%*c%c", &x, &y, &z);
//print
printf("x= \'%c\' \n", x);
printf("y= \'%c\' \n", y);
printf("z= \'%c\' \n", z);
return 0;
}
Output
输出量
Enter 3 character values: a b c
x= 'a'
y= 'b'
z= 'c'
翻译自: https://www.includehelp.com/c-programs/input-individual-characters-using-scanf.aspx
scanf_s输入单个字符