当前位置:   article > 正文

scanf_s输入单个字符_在C中使用scanf()输入单个字符

scanf_s输入字符

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:不跳过字符之间的空格

  1. #include <stdio.h>
  2. int main(void)
  3. {
  4. char x;
  5. char y;
  6. char z;
  7. //input
  8. printf("Enter 3 character values: ");
  9. scanf ("%c%c%c", &x, &y, &z);
  10. //print
  11. printf("x= \'%c\' \n", x);
  12. printf("y= \'%c\' \n", y);
  13. printf("z= \'%c\' \n", z);
  14. return 0;
  15. }

Output

输出量

  1. Enter 3 character values: a b c
  2. x= 'a'
  3. y= ' '
  4. 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:通过跳过空格或字符之间的任何字符

  1. #include <stdio.h>
  2. int main(void)
  3. {
  4. char x;
  5. char y;
  6. char z;
  7. //input
  8. printf("Enter 3 character values: ");
  9. scanf ("%c%*c%c%*c%c", &x, &y, &z);
  10. //print
  11. printf("x= \'%c\' \n", x);
  12. printf("y= \'%c\' \n", y);
  13. printf("z= \'%c\' \n", z);
  14. return 0;
  15. }

Output

输出量

  1. Enter 3 character values: a b c
  2. x= 'a'
  3. y= 'b'
  4. z= 'c'

翻译自: https://www.includehelp.com/c-programs/input-individual-characters-using-scanf.aspx

scanf_s输入单个字符

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号