美文网首页
回忆C —— scanf

回忆C —— scanf

作者: FiboThree | 来源:发表于2018-02-10 14:58 被阅读9次

  • 3 = scanf( "1" , 2);

    1. 1位置是用来规定输入格式,匹配类型的,按照给定格式匹配完后,回车结束

      %[]   //用来指定与其中相匹配的字符的 (%[abc]除了abc都不接收)
      %[^]   //用来指定与其中不相匹配的字符的 (%[^a]除了a都接收)
      
      %.2f  //%宽度.精度f
      
      
    2. 2位置使用来接受输入的值,务必传入地址

      int a;
      float b;
      char c;
      char str[20];
      scanf("%d",&a);
      scanf("%f",&b);
      scanf("%c",&c);
      scanf("%s",str); //本身就是字符数组的首地址 str <=> &str
      
    3. 返回值

          scanf("%d%d",&a,&b);
          //成功接收2个   返回 2
          //一个都没成功  返回 0
          //遇到错        返回 EOF
      
  • 空格 回车 Tab (空白字符white space)

    1. 数字

      int a, b, c;
      scanf("%d%d%d", &a, &b, &c); //默认以空白为分割符,如果scanf 碰到space tab 会留后边的字符串在缓冲区
      
    2. 字符串

      char str[20];
      scanf("%s", str);
      printf("1-%s", str);
      scanf("%s", str);
      printf("2-%s", str);//空格不纳入匹配str中,不会被接收的
      
      scanf("%[^\n]",str);//除了回车用来结束输入,空格也会连同其他字符一起接收
      
      
    3. 字符

      char c;
      scanf("%s", str);//接收空格
      
  • 清除缓冲区

    1. microsoft —— fflush(stdin);
      while(scanf("%c%c",&a,&b)!=EOF){  
          printf("a=%c,b=%c\n",a,b);  
          fflush(stdin);  
          printf("Input the value of a and b:");  
      }  
      
    2. getchar()
          getchar()
      
    3. gets(char*)
          char str[20];
          gets(str);
      
    参考文章:
        http://blog.csdn.net/u011499425/article/details/52606973
        这篇非常全
        http://blog.csdn.net/21aspnet/article/details/174326
        http://blog.csdn.net/hunanchenxingyu/article/details/25542555

相关文章

网友评论

      本文标题:回忆C —— scanf

      本文链接:https://www.haomeiwen.com/subject/vgnctftx.html